Implementing Inheritance 391
12
Virtual Methods ..................................................................................................
This lesson has emphasized the fact that a Dogobject is a Mammalobject. So far that has
meant only that the Dogobject has inherited the attributes (data) and capabilities (meth-
ods) of its base class. In C++, the is-a relationship runs deeper than that, however.
C++ extends its polymorphism to allow pointers to base classes to be assigned to derived
class objects. Thus, you can write
Mammal* pMammal = new Dog;
This creates a new Dogobject on the heap and returns a pointer to that object, which it
assigns to a pointer to Mammal. This is fine because a dog is a mammal.
When calling overridden ancestor class functions using “::”, keep in mind
that if a new class is inserted in the inheritance hierarchy between the
descendant and its ancestor, the descendant will be now making a call that
skips past the intermediate class and, therefore, might miss invoking some
key capability implemented by the intermediate ancestor.
TIP
DOextend the functionality of existing,
tested classes by deriving.
DOchange the behavior of certain func-
tions in the derived class by overriding
the base class methods.
DON’Thide a base class function by
changing the function signature.
DON’Tforget that constis a part of the
signature.
DON’Tforget that the return type is not
part of the signature.
DO DON’T
This is the essence of polymorphism. For example, you could create many
types of windows, including dialog boxes, scrollable windows, and list boxes,
and give them each a virtual draw()method. By creating a pointer to a win-
dow and assigning dialog boxes and other derived types to that pointer, you
can call draw()without regard to the actual runtime type of the object
pointed to. The correct draw()function will be called.
NOTE
You can then use this pointer to invoke any method on Mammal. What you would like is
for those methods that are overridden in Dog()to call the correct function. Virtual