Sams Teach Yourself C++ in 21 Days

(singke) #1
This program certainly works, although at the expense of the Horseclass having
a Fly()method. On line 10, the method Fly()is provided to Horse. In a real-
world class, you might have it issue an error, or fail quietly. On line 18, the Pegasus
class overrides the Fly()method to “do the right thing,” represented here by printing a
happy message.
The array of Horsepointers called Ranchon line 25 is used to demonstrate that the cor-
rect Fly()method is called, based on the runtime binding of the Horseor Pegasus
object.
In lines 28–37, the user is prompted to select a Horseor a Pegasus. An object of the cor-
responding type is then created and placed into the Rancharray.
In lines 38–43, the program loops again through the Rancharray. This time, each object
in the array has its Fly()method called. Depending on whether the object is a Horseor
a Pegasus, the correct Fly()method is called. You can see this in the output. Because
this program will no longer use the objects in Ranch, in line 42 a call to deleteis made
to free the memory used by each object.

452 Day 14


ANALYSIS

These examples have been stripped down to their bare essentials to illus-
trate the points under consideration. Constructors, virtual destructors, and
so on have been removed to keep the code simple. This is not recommended
for your programs.

NOTE

Percolating Upward ........................................................................................


Putting the required function higher in the class hierarchy is a common solution to this
problem and results in many functions “percolating up” into the base class. The base
class is then in grave danger of becoming a global namespace for all the functions that
might be used by any of the derived classes. This can seriously undermine the class typ-
ing of C++, and can create a large and cumbersome base class.
In general, you want to percolate shared functionality up the hierarchy, without migrating
the interface of each class. This means that if two classes that share a common base class
(for example,Horseand Birdboth share Animal) and have a function in common (both
birds and horses eat, for example), you’ll want to move that functionality up into the
base class and create a virtual function.
What you’ll want to avoid, however, is percolating a function (such as Fly)up where it
doesn’t belong just so you can call that function only on some derived classes, when it
doesn’t fit the meaning of that base class.
Free download pdf