Sams Teach Yourself C++ in 21 Days

(singke) #1

464 Day 14


Any time you need to resolve which class a member function or member data inherits
from, you can fully qualify the call by prepending the class name to the base class data
or function.
Note that if Pegasuswere to override this function, the problem would be moved, as it
should be, into the Pegasusmember function:
virtual COLOR GetColor()const { return Horse::GetColor(); }
This hides the problem from clients of the Pegasusclass and encapsulates within
Pegasusthe knowledge of which base class from which it wants to inherit its color. A
client is still free to force the issue by writing
COLOR currentColor = pPeg->Bird::GetColor();

Inheriting from Shared Base Class ................................................................


What happens if both Birdand Horseinherit from a common base class, such as
Animal? Figure 14.2 illustrates what this looks like.

FIGURE14.2
Common base classes.
Animal

Horse

Animal

Bird

Pegasus

As you can see in Figure 14.2, two base class objects exist. When a function or data
member is called in the shared base class, another ambiguity exists. For example, if
Animaldeclares itsAgeas a member variable and GetAge()as a member function, and
you call pPeg->GetAge(), did you mean to call the GetAge()function you inherit from
Animalby way of Horse, or by way of Bird? You must resolve this ambiguity as well, as
illustrated in Listing 14.5.
Free download pdf