Sams Teach Yourself C++ in 21 Days

(singke) #1

472 Day 14


Pegasusno longer has to disambiguate the call to GetAge(), and so is free to simply
inherit this function from Animal. Note that Pegasusmust still disambiguate the call to
GetColor()because this function is in both of its base classes and not in Animal.

Declaring Classes for Virtual Inheritance
To ensure that derived classes have only one instance of common base classes, declare the
intermediate classes to inherit virtually from the base class.
Example 1
class Horse : virtual public Animal
class Bird : virtual public Animal
class Pegasus : public Horse, public Bird
Example 2
class Schnauzer : virtual public Dog
class Poodle : virtual public Dog
class Schnoodle : public Schnauzer, public Poodle

Problems with Multiple Inheritance ..............................................................


Although multiple inheritance offers several advantages over single inheritance, many
C++ programmers are reluctant to use it. The problems they cite are that it makes debug-
ging harder, that evolving multiple inheritance class hierarchies is harder and more risky
than evolving single inheritance class hierarchies, and that nearly everything that can be
done with multiple inheritance can be done without it. Other languages, such as Java and
C#, don’t support multiple inheritance of classes for some of these same reasons.
These are valid concerns, and you will want to be on your guard against installing need-
less complexity into your programs. Some debuggers have a hard time with multiple
inheritance, and some designs are needlessly made complex by using multiple inheri-
tance when it is not needed.

DOuse multiple inheritance when a new
class needs functions and features from
more than one base class.
DOuse virtual inheritance when the
most derived classes must have only one
instance of the shared base class.
DOinitialize the shared base class from
the most derived class when using virtual
base classes.

DON’Tuse multiple inheritance when
single inheritance will do.

DO DON’T

Free download pdf