Sams Teach Yourself C++ in 21 Days

(singke) #1
Polymorphism 459

14


Ranch[0]: Whinny!... Horse destructor...
Ranch[1]: Whinny!... Pegasus destructor... Bird destructor...
Horse destructor...
Aviary[0]: Chirp... I can fly! I can fly! I can fly! Bird destructor...
Aviary[1]: Whinny!... I can fly! I can fly! I can fly!
Pegasus destructor... Bird destructor... Horse destructor...
On lines 7–15, a Horseclass is declared. The constructor and destructor print out
a message, and the Whinny()method prints Whinny!....
On lines 17–29, a Birdclass is declared. In addition to its constructor and destructor, this
class has two methods:Chirp()and Fly(), both of which print identifying messages. In
a real program, these might, for example, activate the speaker or generate animated
images.
Finally, on lines 31–37, you see the new code—using multiple inheritance, the class
Pegasusis declared. In line 31, you can see that this class is derived from both Horse
and Bird. The Pegasusclass overrides the Chirp()method in line 34. The Pegasus’
Chirp()method simply does a call to the Whinny()method, which it inherits from
Horse.
In the main section of this program, two lists are created: a Ranchwith pointers to Horse
objects on line 42, and an Aviarywith pointers to Birdobjects on line 43. On lines
47–56,Horseand Pegasusobjects are added to the Ranch. On lines 57–66,Birdand
Pegasusobjects are added to the Aviary.
Invocations of the virtual methods on both the Birdpointers and the Horsepointers do
the right things for Pegasusobjects. For example, on line 79 the members of the Aviary
array are used to call Chirp()on the objects to which they point. The Birdclass declares
this to be a virtual method, so the right function is called for each object.
Note that each time a Pegasusobject is created, the output reflects that both the Bird
part and the Horsepart of the Pegasusobject are also created. When a Pegasusobject is
destroyed, the Birdand Horseparts are destroyed as well, thanks to the destructors being
made virtual.

ANALYSIS


Declaring Multiple Inheritance
Declare an object to inherit from more than one class by listing the base classes following
the colon after the class name. Separate the base classes by commas.
Example 1
class Pegasus : public Horse, public Bird
Example 2
class Schnoodle : public Schnauzer, public Poodle
Free download pdf