I am just making sure I understand the difference between the two codes correctly.
I am creating two instances of class CRectangle but working with them as if they were instances of CPolygon.
#include <iostream>
usingnamespace std;
class CPolygon{
protected:
double width, height;
public:
void set_values (int a, int b){ width=a; height=b;};
virtualdouble area(){return 0;};
};
class CRectangle: public CPolygon{
public:
double area (){ return (width * height); }
};
int main () {
CPolygon * pRect = new CRectangle;
CPolygon rect = *(new CRectangle);
pRect->set_values(4,5);
rect.set_values(4,5);
cout << pRect->area() << endl;
cout << rect.area() << endl;
return 0;
}
- In the case of 'pRect' the output is 20, because in the CPolygon the function area() is declared as virtual.
- On the other hand, for 'rect' the output is 0. Is this because there is an implicit casting going on? That is 'rect' is really an instance of CPolygon?