implicit casting?

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

class CPolygon{
   protected:
      double width, height;
   public:
      void set_values (int a, int b){ width=a; height=b;};
      virtual double 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?
rect is an object of type CPolygon as it was defined by your. *(new Crectangle) was implicitly converted to Cpolygon.
Topic archived. No new replies allowed.