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.