Polymorphism 463
14
On lines 9–20, the Horseclass is declared. The constructor takes two parameters:
One is an enumeration for colors, which is declared on line 7, and the other is a
typedefdeclared on line 6. The implementation of the constructor on lines 22–26 simply
initializes the member variables and prints a message.
On lines 28–44, the Birdclass is declared, and the implementation of its constructor is
on lines 46–50. Again, the Birdclass takes two parameters. Interestingly, the Horsecon-
structor takes color (so that you can detect horses of different colors), and the Birdcon-
structor takes the color of the feathers (so those of one feather can stick together). This
leads to a problem when you want to ask the Pegasusfor its color, which you’ll see in
the next example.
The Pegasusclass itself is declared on lines 52–65, and its constructor is on lines 67–77.
The initialization of the Pegasusobject includes three statements. First, the Horsecon-
structor is initialized with color and height (line 72). Then, the Birdconstructor is initial-
ized with color and the Boolean indicating if it migrates (line 73). Finally, the Pegasus
member variable itsNumberBelieversis initialized. After all that is accomplished, the
body of the Pegasusconstructor is called.
In the main()function, a Pegasuspointer is created in line 81. This object is then used
to access the member functions that were derived from the base classes. The access of
these methods is straightforward.
Ambiguity Resolution ....................................................................................
In Listing 14.4, both the Horseclass and the Birdclass have a method GetColor().
You’ll notice that these methods were not called in Listing 14.4! You might need to ask
the Pegasusobject to return its color, but you have a problem—the Pegasusclass inher-
its from both Birdand Horse. They both have a color, and their methods for getting that
color have the same names and signature. This creates an ambiguity for the compiler,
which you must resolve.
If you simply write
COLOR currentColor = pPeg->GetColor();
you receive a compiler error:
Member is ambiguous: ‘Horse::GetColor’ and ‘Bird::GetColor’
You can resolve the ambiguity with an explicit call to the function you want to invoke:
COLOR currentColor = pPeg->Horse::GetColor();
ANALYSIS