Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism with different methods in derived classes

While trying to learn polymorphism I am confused about one thing. Consider the following situation:

There exists a base class Shape and the derived classes Circle and Square. With polymorphism I can implement the method get_area as virtual function in the base class and implement individual versions of this funtion in the derives classes Circle and Square.

class Shape
{
  public:
    Shape(){}
    virtual int get_area() = 0;
};

class Square: public Shape
{
  public:
    Square(int width, int height)
    {
       // stuff
    }
    int get_area()
    { 
       return width*height; 
    }
};

class Circle: public Shape
{
  public:
    Circle(int radius)
    {
       // stuff
    }
    int get_area()
    { 
       return pi*radius*radius; 
    }
};

int main () 
{
  Shape *circle= new Circle(3);
  Shape *square= new Square(4,5);

  return 0;
}

But what if I need to implement a individual method in one of the derived classes, for example get_radius. I get error-messsages from the compiler, if this method is not implmeneted as virtual function in the base class. But If I do this, I also have to implement the method get_radius in the derived class Square and this does not make any sense, because a square does not have a radius.

Is there a better way to cope with this problem? Thanks.

like image 251
Lemonbonbon Avatar asked Oct 19 '25 14:10

Lemonbonbon


1 Answers

If you write

Shape *circle=new Circle(4,5);

and then you try to use this reference to call the get_radius() method

circle->get_radius(); 

an error occurs, if you didn't declare a get_radius method, virtual or concrete, in the Shape class. The error occurs because circle is not a reference to a Circle, but a reference to a Shape, so the definition of the method cannot be resolved simply because there's no get_radius method defined in Shape.
On the the other hand, if you declared get_radius in the Shape class, you can (if it has a concrete implementantion) call get_radius for all kind of Shapes and it has no much sense.
So the right way is use a reference to a Circle e.g.

Circle *circle=new Circle(4,5);
double r=circle->get_radius();
... //do something with r 
like image 130
Jul10 Avatar answered Oct 22 '25 04:10

Jul10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!