468 Day 14
The constructor initializes the Horsepart of the Pegasuswith the color, height, and age
on line 88. It initializes the Birdpart with color, whether it migrates, and age on line 89.
Finally, it initializes itsNumberBelieverson line 90.
The call to the Horseconstructor on line 88 invokes the implementation shown on line
- The Horseconstructor uses the age parameter to initialize the Animalpart of the
Horsepart of the Pegasus. It then goes on to initialize the two member variables of
Horse—itsColorand itsHeight.
The call to the Birdconstructor on line 89 invokes the implementation shown on line 61.
Here, too, the age parameter is used to initialize the Animalpart of the Bird.
Note that the color parameter to the Pegasusis used to initialize member variables in
each of Birdand Horse. Note also that the age is used to initialize itsAgein the Horse’s
base Animaland in the Bird’s base Animal.
Keep in mind that whenever you explicitly disambiguate an ancestor class,
you create a risk that a new class inserted between your class and its ances-
tor will cause this class to inadvertently call “past” the new ancestor into the
old ancestor, and this can have unexpected effects.
CAUTION
Virtual Inheritance ..........................................................................................
In Listing 14.5, the Pegasusclass went to some lengths to disambiguate which of its
Animalbase classes it meant to invoke. Most of the time, the decision as to which one to
use is arbitrary—after all, the Horseand the Birdhave the same base class.
It is possible to tell C++ that you do not want two copies of the shared base class,
as shown in Figure 14.2, but rather to have a single shared base class, as shown in
Figure 14.3.
You accomplish this by making Animala virtual base class of both Horseand Bird. The
Animalclass does not change at all. The Horseand Birdclasses change only in their use
of the term virtualin their declarations. Pegasus, however, changes substantially.
Normally, a class’s constructor initializes only its own variables and its base class.
Virtually inherited base classes are an exception, however. They are initialized by their
most derived class. Thus,Animalis initialized not by Horseand Bird, but by Pegasus.
Horseand Birdhave to initialize Animalin their constructors, but these initializations
will be ignored when a Pegasusobject is created.