Sams Teach Yourself C++ in 21 Days

(singke) #1
Suddenly, you realize you need a Pegasusobject: a cross between a Horseand a Bird. A
Pegasuscan Fly(), it can Whinny(), and it can Gallop(). With single inheritance, you’re
in quite a jam.
With single inheritance, you can only pull from one of these existing classes. You can
make Pegasusa Bird, but then it won’t be able to Whinny()or Gallop(). You can make
it a Horse, but then it won’t be able to Fly().
Your first solution is to copy the Fly()method into the Pegasusclass and derive
Pegasusfrom Horse. This works fine, at the cost of having the Fly()method in two
places (Birdand Pegasus). If you change one, you must remember to change the other.
Of course, a developer who comes along months or years later to maintain your code
must also know to fix both places.
Soon, however, you have a new problem. You want to create a list of Horseobjects and a
list of Birdobjects. You’d like to be able to add your Pegasusobjects to either list, but if
a Pegasusis a Horse, you can’t add it to a list of Birds.
You have a couple of potential solutions. You can rename the Horsemethod Gallop()to
Move(), and then override Move()in your Pegasusobject to do the work of Fly(). You
would then override Move()in your other horses to do the work of Gallop(). Perhaps
Pegasuscould be clever enough to gallop short distances and fly longer distances.
Pegasus::Move(long distance)
{
if (distance > veryFar)
fly(distance);
else
gallop(distance);
}
This is a bit limiting. Perhaps one day Pegasuswill want to fly a short distance or gallop
a long distance. Your next solution might be to move Fly()up into Horse, as illustrated
in Listing 14.1. The problem is that most horses can’t fly, so you have to make this
method do nothing unless it is a Pegasus.

LISTING14.1 If Horses Could Fly...
0: // Listing 14.1. If horses could fly...
1: // Percolating Fly() up into Horse
2:
3: #include <iostream>
4: using namespace std;
5:
6: class Horse
7: {
8: public:

450 Day 14

Free download pdf