Polymorphism 471
14
75: virtual COLOR GetColor()const { return Horse::itsColor; }
76: private:
77: long itsNumberBelievers;
78: };
79:
80: Pegasus::Pegasus(
81: COLOR aColor,
82: HANDS height,
83: bool migrates,
84: long NumBelieve,
85: int age):
86: Horse(aColor, height,age),
87: Bird(aColor, migrates,age),
88: Animal(age*2),
89: itsNumberBelievers(NumBelieve)
90: {
91: cout << “Pegasus constructor...\n”;
92: }
93:
94: int main()
95: {
96: Pegasus *pPeg = new Pegasus(Red, 5, true, 10, 2);
97: int age = pPeg->GetAge();
98: cout << “This pegasus is “ << age << “ years old.\n”;
99: delete pPeg;
100: return 0;
101: }
Animal constructor...
Horse constructor...
Bird constructor...
Pegasus constructor...
This pegasus is 4 years old.
Pegasus destructor...
Bird destructor...
Horse destructor...
Animal destructor...
On line 25,Horsedeclares that it inherits virtually from Animal, and on line 45,
Birdmakes the same declaration. Note that the constructors for both Birdand
Animalstill initialize the Animalobject.
Pegasusinherits from both Birdand Animal, and as the most derived object of Animal,it
also initializes Animal. It is Pegasus’s initialization which is called, however, and the
calls to Animal’s constructor in Birdand Horseare ignored. You can see this because the
value 2 is passed in, and Horseand Birdpass it along to Animal, but Pegasusdoubles it.
The result, 4 , is reflected in the output generated from line 98.
OUTPUT
LISTING14.6 continued
ANALYSIS