1 2 3 4 5 6 7 8 9 10 11

Virtual Functions
Class derivation is even more valuable when combined with virtual functions--functions that are declared in a base class, but implemented differently in each derived class. Consider the Shapeclass:It will need a grow function so that every Shapecan increase its size.
class Shape {
public:
void grow();
....
};
But the grow function must be different for each class derived from Shape. Thus we make grow a virtual function
class Shape {
public:
virtualvoid grow ();
........
};
The Circle, Square and Triangle classes will now provide their own custom versions of grow. The circle version might look like:
class Circle: public Shape {
public:
void grow () { radius++; }
......
private:
int radius;// radius of circle
....
}
If cis a Circleobject, the call c.grow()increases the radius of c. When grow()is invoked through a pointer to a base class, the virtual function uses the correct grow function depending on the kind of object pointed to.

March 14, 1998

Page 1

C201/TAM