// virtual members
#include <iostream>
usingnamespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtualint area ()
{ return (0); }
};
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area ()
{ return (width * height / 2); }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon poly;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
CPolygon * ppoly3 = &poly;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
cout << ppoly1->area() << endl;
cout << ppoly2->area() << endl;
cout << ppoly3->area() << endl;
return 0;
}
my question is with the code below.
CPolygon * ppoly1 = ▭
i see that we are declaring a pointer of class CPolygon. so what does the &rect on the other side of the equal sign mean is it an object of class CPolygon?
and also can somebody explain the code below in simplest form terms (mainly the -> operator)?
Since rect is of type CRectangle (which is polymorphic to CPolygon) we can use a base class pointer, ppoly1 to point to that object. Basically, since a rectangle is also a shape (polygon) we can point to it as a shape.
-> is an operator that accesses the member of a pointed-to object. Since ppoly1 is a CPolygon* and set_values is a member of the CPolygon class, ppoly1->set_values is legit. (Further explanation: ppoly1->set_values would equal the exact same as: (*ppoly1).set_values)
So basically this is the template for polymorphism
class_identifier * class_pointer = object
so the class_identifier is CPolygon, the class_pointer is *poly1, and the object would be &rect. This is because the class identifies what the object and pointer belongs to.
The polymorphic_class_pointer_identifier is an identifier (name) of a pointer to a polymorphic class. An example would be that if we were to declare an identifier for the address of rect, it would be a polymorphic class pointer identifier (in this context). (Do realize that these are just fancy names, there are most likely better names for these cases.)
What it does is create a general way to point to polymorphic classes. Since a rectangle is a polygon, a polygon pointer can refer to a rectangle. No additional overhead is needed when rectangles and triangles are mixed in, let's say, a vector. Since with base class pointers, we can just refer to a single type in the end.