456 Day 14
Adding to Two Lists ......................................................................................
The other problem with these solutions is that you’ve declared Pegasusto be a type of
Horse, so you cannot add a Pegasusobject to a list of Birds. You’ve paid the price of
either moving Fly()up into Horseor casting down the pointer, and yet you still don’t
have the full functionality you need.
One final, single inheritance solution presents itself. You can push Fly(),Whinny(), and
Gallop()all up into a common base class of both Birdand Horse:Animal. Now, instead
of having a list of Birds and a list of Horses, you can have one unified list of Animals.
This works, but eventually leads to a base class that has all of the characteristics of all of
its descendant classes. So who needs descendant classes then?
Alternatively, you can leave the methods where they are and cast down Horses and Birds
and Pegasusobjects, but that is even worse!
DOmove functionality up the inheri-
tance hierarchy when it is conceptually
cohesive with the meaning of the ances-
tor class.
DOavoid performing actions based on
the runtime type of the object—use vir-
tual methods, templates, and multiple
inheritance.
DON’T clutter ancestor classes with capa-
bilities that are only added to support a
need for polymorphism in descendant
classes.
DON’Tcast pointers to base objects
down to derived objects.
DO DON’T
Multiple Inheritance ............................................................................................
It is possible to derive a new class from more than one base class. This is called multiple
inheritance. To derive from more than the base class, you separate each base class by
commas in the class designation, as shown here:
class DerivedClass: public BaseClass1, public BaseClass2{}
This is exactly like declaring single inheritance with an additional base class,
BaseClass2, added.
Listing 14.3 illustrates how to declare Pegasusso that it derives from both Horses and
Birds. The program then adds Pegasusobjects to both types of lists.