![[Dept of Engineering]](http://www.eng.cam.ac.uk/images/house_style/engban-s.gif)
Suppose that we were designing a graphics editor. We might have a base class Shape and various derived classes Triangle, Rectangle, etc, each with their own print member function. We'd like to collect these objects together into groups sometimes. An array of pointers to the objects would be appropriate, but what sort of pointers could we use? Fortunately, it's possible to assign a derived class pointer to a base class pointer, so the following is possible, creating an array of pointers to the base class.
Triangle t1, t2; Rectangle r1, r2; typedef ShapePtr Shape*; vector<ShapePtr> shapes(4); shapes[0]=&t1; shapes[1]=&r1; shapes[2]=&t2; shapes[3]=&r2;
Then we could draw all the shapes in the group by calling the print function of each element. But there's a problem - because the elements are pointers to Shape, it's Shape's print function which is called, rather than the appropriate derived object's function.
The solution to this is to define print in the base class as a virtual function by having something like
virtual void print();
which lets us deal with the shapes array without having to worry about the real type of each component; the derived object's print function will always be called.