Polymorphism 467
14
98: int age = pPeg->GetAge();
99: cout << “This pegasus is “ << age << “ years old.\n”;
100: delete pPeg;
101: return 0;
102: }
Animal constructor...
Horse constructor...
Animal constructor...
Bird constructor...
Pegasus constructor...
This pegasus is 2 years old.
Pegasus destructor...
Bird destructor...
Animal destructor...
Horse destructor...
Animal destructor...
Several interesting features are in this listing. The Animalclass is declared on lines
9–18. Animaladds one member variable,itsAge, and two accessors:GetAge()
and SetAge().
On line 26, the Horseclass is declared to derive from Animal. The Horseconstructor
now has a third parameter, age, which it passes to its base class,Animal(see line 40).
Note that the Horseclass does not override GetAge(), it simply inherits it.
On line 46, the Birdclass is declared to derive from Animal. Its constructor also takes an
age and uses it to initialize its base class,Animal(see line 62). It also inherits GetAge()
without overriding it.
Pegasusinherits from both Birdand Horsein line 68, and so has two Animalclasses in
its inheritance chain. If you were to call GetAge()on a Pegasusobject, you would have
to disambiguate, or fully qualify, the method you want if Pegasusdid not override the
method.
This is solved on line 77 when the Pegasusobject overrides GetAge()to do nothing
more than to chain up—that is, to call the same method in a base class.
Chaining up is done for two reasons: either to disambiguate which base class to call, as
in this case, or to do some work and then let the function in the base class do some more
work. At times, you might want to do work and then chain up, or chain up and then do
the work when the base class function returns.
The Pegasusconstructor, which starts on line 82, takes five parameters: the creature’s
color, its height (in HANDS), whether it migrates, how many believe in it, and its age.
OUTPUT
LISTING14.5 continued
ANALYSIS