Polymorphism methods


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
class Shape 
{
   public:
      void draw() const {cout<<"draw shape"<<endl;}
};

class Point : public Shape 
{
   public:
      Point( int a= 0, int b = 0 ) {x=a; y=b;}  
      int getx() const {return x;}
      int gety() const {return y;}
      void draw() const {cout<<"draw point("<<x<<","<<y<<")\n";}
   private:
      int x, y;  
};

class Circle : public Point 
{
   public:      
      Circle( double r = 0.0, int x = 0, int y = 0 ):Point(x,y) 
	{ radius = r; }
      void draw() const 
	{ cout<<"draw circle("<<getx()<<","<<gety()<<","<<radius<<")\n"; }
   private:
      double radius;  
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
   Shape shape;
   Point point( 7, 11 );            
   Circle circle( 3.5, 22, 8 );     

   Shape *arrayOfShapes[3];

   arrayOfShapes[0] = &shape;
   arrayOfShapes[1] = &point;
   arrayOfShapes[2] = &circle;

   for(int i=0; i<3; ++i)
    arrayOfShapes[i]->draw();

   return 0;
}



Why does the above code print "draw shape", which is the draw() of the base class ? Why are the methods from the derived classes ignored ?
Because draw() in the base class is not declared virtual.
Wouldn't the draw() method in the derived class take priority over the draw() method in the base class ? I've read of the concept name hiding. Confused.
Last edited on
Wouldn't the draw() method in the derived class take priority over the draw() method in the base class ?


No. That happens only if draw() is declared virtual in the base class.
http://www.cplusplus.com/doc/tutorial/polymorphism/

You don't use virtual in the base class. In that case you would have to reference an object of the derived class to have the derived class' draw() function called. That's not what you are doing.

arrayOfShapes are pointers to the base class (Shape). Shape's draw() function is going to be called because Shape::draw() is not virtual.

Make Shape::draw() virtual and you will get the behavior you expect. Note that you need to make Point::draw virtual also as Circle derives from Point.

Just a comment: Your inheritance structure is a little odd. Typically, a Circle IS A Shape and a Circle HAS A point.
Thanks a lot for the info :D

Hmm so long as the array type is Shape, will all methods called be from Shape ?
so long as the array type is Shape, will all methods called be from Shape ?

How many times do I have to say this? For an object of type Shape or derived from Shape, Shape's methods will be called as long as they are not virtual.
Last edited on
Topic archived. No new replies allowed.