[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Abstract Classes Up: More on Classes Previous: More on Classes

Virtual members

As mentioned earlier, it's easy to redefine a base class's function in a derived class, but to fully exploit polymorphism (the ability to deal with many types transparently), a new concept needs to be introduced.

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.


next up previous contents
Next: Abstract Classes Up: More on Classes Previous: More on Classes
Tim Love
2001-07-05