Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Virtual Member Functions

In Program gif Draw, Erase and MoveTo are all declared as virtual member functions of the GraphicalObject class. Declaring a member function virtual changes the way in which the compiler determines the member function to call.

Consider the following sequence of instructions:

GraphicalObject& g1 = *new Circle (Point (0,0), 5);
GraphicalObject& g2 = *new Square (Point (0,0), 5);
g1.Draw ();
g2.Draw ();
If the Draw function was not declared virtual, then both g1.Draw() and g2.Draw() would invoke GraphicalObject::Draw. However, because Draw is a virtual function, g1.Draw() calls Circle::Draw and g2.Draw() calls Rectangle::Draw.

It is as if every object of a class contains a pointer to the actual routine to be invoked when a virtual function is called on that object. E.g, Circle objects carry pointers to Circle::Draw, GraphicalObject::Erase and GraphicalObject::MoveTo, whereas Square objects carry pointers to Rectangle::Draw, GraphicalObject::Erase and GraphicalObject::MoveTo.

Virtual functions ensure that the ``correct'' member function is actually called, regardless of how the object is accessed. Consider the following sequence:

Square s (Point (0,0), 5);
Rectangle& r = s;
GraphicalObject& g = r;
Here s, r and g all refer to the same object, even though they are all of different types. However, because Draw is virtual, s.Draw(), r.Draw() and g.Draw() all invoke Rectangle::Draw.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.