An example of polymorphism
class Shape {
public:
virtual void draw()
{ cout<<"Shape::draw()"<<endl; }
};
class Circle : public Shape {
public:
virtual void draw()
{ cout<<"Circle::draw()"<<endl; }
};
class Rectangle : public Shape {
public:
virtual void draw()
{ cout<<"Rectangle::draw()"<<endl; }
};
void drawShape(Shape *sp)
{
sp->draw();
}
A generic function to draw any shape even when more classes are derived from Shape later on.
int main()
{
Shape *sp1 = new Circle;
drawShape(sp1);
delete sp1;
sp1 = new Rectangle;
drawShape(sp1);
return 0;
}
The base class in this case, Shape(), seems somewhat contrived.
Can we ever have a generic shape?
Maybe we just want a common base interface and we never actually need objects of type Shape. If that’s the case we want to make draw() a pure virtual function, and Shape, as a result, an abstract class.
It’s a fairly minor change, set the base virtual function to =0; ...
class Shape {
public:
virtual void draw() = 0;
};
... but it now means we cannot instantiate a Shape object, so the following will fail to compile ...
Shape *sp = new Shape;