Effective C++ Third Edition 55 Specific Ways to Improve Your Programs and Designs

Item 32: Make sure public inheritance models "is-a."

In his book, Some Must Watch While Some Must Sleep (W. H. Freeman and Company, 1974), William Dement relates the story of his attempt to fix in the minds of his students the most important lessons of his course. It is claimed, he told his class, that the average British schoolchild remembers little more history than that the Battle of Hastings was in 1066. If a child remembers little else, Dement emphasized, he or she remembers the date 1066. For the students in his course, Dement went on, there were only a few central messages, including, interestingly enough, the fact that sleeping pills cause insomnia. He implored his students to remember these few critical facts even if they forgot everything else discussed in the course, and he returned to these fundamental precepts repeatedly during the term.

At the end of the course, the last question on the final exam was, "Write one thing from the course that you will surely remember for the rest of your life." When Dement graded the exams, he was stunned. Nearly everyone had written "1066."

It is thus with great trepidation that I proclaim to you now that the single most important rule in object-oriented programming with C++ is this: public inheritance means "is-a." Commit this rule to memory.

If you write that class D ("Derived") publicly inherits from class B ("Base"), you are telling C++ compilers (as well as human readers of your code) that every object of type D is also an object of type B, but not vice versa. You are saying that B represents a more general concept than D, that D represents a more specialized concept than B. You are asserting that anywhere an object of type B can be used, an object of type D can be used just as well, because every object of type D is an object of type B. On the other hand, if you need an object of type D, an object of type B will not do: every D is-a B, but not vice versa.

C++ enforces this interpretation of public inheritance. Consider this example:

class Person {...}; class Student: public Person {...};

We know from everyday experience that every student is a person, but not every person is a student. That is exactly what this hierarchy asserts. We expect that anything that is true of a person for example, that he or she has a date of birth is also true of a student. We do not expect that everything that is true of a student that he or she is enrolled in a particular school, for instance is true of people in general. The notion of a person is more general than is that of a student; a student is a specialized type of person.

Within the realm of C++, any function that expects an argument of type Person (or pointer-to-Person or reference-to-Person) will also take a Student object (or pointer-to-Student or reference-to-Student):

void eat(const Person& p); // anyone can eat void study(const Student& s); // only students study Person p; // p is a Person Student s; // s is a Student eat(p); // fine, p is a Person eat(s); // fine, s is a Student, // and a Student is-a Person study(s); // fine study(p); // error! p isn't a Student

This is true only for public inheritance. C++ will behave as I've described only if Student is publicly derived from Person. Private inheritance means something entirely different (see Item 39), and protected inheritance is something whose meaning eludes me to this day.

The equivalence of public inheritance and is-a sounds simple, but sometimes your intuition can mislead you. For example, it is a fact that a penguin is a bird, and it is a fact that birds can fly. If we naively try to express this in C++, our effort yields:

class Bird { public: virtual void fly(); // birds can fly ... }; class Penguin:public Bird { // penguins are birds ... };

Suddenly we are in trouble, because this hierarchy says that penguins can fly, which we know is not true. What happened?

In this case, we are the victims of an imprecise language: English. When we say that birds can fly, we don't mean that all types of birds can fly, only that, in general, birds have the ability to fly. If we were more precise, we'd recognize that there are several types of non-flying birds, and we would come up with the following hierarchy, which models reality much better:

class Bird { ... // no fly function is declared }; class FlyingBird: public Bird { public: virtual void fly(); ... }; class Penguin: public Bird { ... // no fly function is declared };

This hierarchy is much more faithful to what we really know than was the original design.

Yet we're not finished with these fowl matters, because for some software systems, there may be no need to distinguish between flying and non-flying birds. If your application has much to do with beaks and wings and nothing to do with flying, the original two-class hierarchy might be quite satisfactory. That's a simple reflection of the fact that there is no one ideal design for all software. The best design depends on what the system is expected to do, both now and in the future. If your application has no knowledge of flying and isn't expected to ever have any, failing to distinguish between flying and non-flying birds may be a perfectly valid design decision. In fact, it may be preferable to a design that does distinguish between them, because such a distinction would be absent from the world you are trying to model.

There is another school of thought on how to handle what I call the "All birds can fly, penguins are birds, penguins can't fly, uh oh" problem. That is to redefine the fly function for penguins so that it generates a runtime error:

void error(const std::string& msg); // defined elsewhere class Penguin: public Bird { public: virtual void fly() { error("Attempt to make a penguin fly!");} ... };

It's important to recognize that this says something different from what you might think. This does not say, "Penguins can't fly." This says, "Penguins can fly, but it's an error for them to actually try to do it."

How can you tell the difference? From the time at which the error is detected. The injunction, "Penguins can't fly," can be enforced by compilers, but violations of the rule, "It's an error for penguins to actually try to fly," can be detected only at runtime.

To express the constraint, "Penguins can't fly period," you make sure that no such function is defined for Penguin objects:

class Bird { ... // no fly function is declared }; class Penguin: public Bird { ... // no fly function is declared };

If you now try to make a penguin fly, compilers will reprimand you for your transgression:

Penguin p; p.fly(); // error!

This is very different from the behavior you get if you adopt the approach that generates runtime errors. With that methodology, compilers won't say a word about the call to p.fly. Item 18 explains that good interfaces prevent invalid code from compiling, so you should prefer the design that rejects penguin flight attempts during compilation to the one that detects them only at runtime.

Perhaps you'll concede that your ornithological intuition may be lacking, but you can rely on your mastery of elementary geometry, right? I mean, how complicated can rectangles and squares be?

Well, answer this simple question: should class Square publicly inherit from class Rectangle?

"Duh!" you say, "Of course it should! Everybody knows that a square is a rectangle, but generally not vice versa." True enough, at least in school. But I don't think we're in school anymore.

Consider this code:

class Rectangle { public: virtual void setHeight(int newHeight); virtual void setWidth(int newWidth); virtual int height() const; // return current values virtual int width() const; ... }; void makeBigger(Rectangle& r) // function to increase r's area { int oldHeight = r.height(); r.setWidth(r.width() + 10); // add 10 to r's width assert(r.height() == oldHeight); // assert that r's } // height is unchanged

Clearly, the assertion should never fail. makeBigger only changes r's width. Its height is never modified.

Now consider this code, which uses public inheritance to allow squares to be treated like rectangles:

class Square: public Rectangle {...}; Square s; ... assert(s.width() == s.height()); // this must be true for all squares makeBigger(s); // by inheritance, s is-a Rectangle, // so we can increase its area assert(s.width() == s.height()); // this must still be true // for all squares

It's just as clear that this second assertion should also never fail. By definition, the width of a square is the same as its height.

But now we have a problem. How can we reconcile the following assertions?

  • Before calling makeBigger, s's height is the same as its width;

  • Inside makeBigger, s's width is changed, but its height is not;

  • After returning from makeBigger, s's height is again the same as its width. (Note that s is passed to makeBigger by reference, so makeBigger modifies s itself, not a copy of s.)

Well?

Welcome to the wonderful world of public inheritance, where the instincts you've developed in other fields of study including mathematics may not serve you as well as you expect. The fundamental difficulty in this case is that something applicable to a rectangle (its width may be modified independently of its height) is not applicable to a square (its width and height must be the same). But public inheritance asserts that everything that applies to base class objects everything! also applies to derived class objects. In the case of rectangles and squares (as well as an example involving sets and lists in Item 38), that assertion fails to hold, so using public inheritance to model their relationship is simply incorrect. Compilers will let you do it, but as we've just seen, that's no guarantee the code will behave properly. As every programmer must learn (some more often than others), just because the code compiles doesn't mean it will work.

Don't fret that the software intuition you've developed over the years will fail you as you approach object-oriented design. That knowledge is still valuable, but now that you've added inheritance to your arsenal of design alternatives, you'll have to augment your intuition with new insights to guide you in inheritance's proper application. In time, the notion of having Penguin inherit from Bird or Square inherit from Rectangle will give you the same funny feeling you probably get now when somebody shows you a function several pages long. It's possibly the right way to approach things, it's just not very likely.

The is-a relationship is not the only one that can exist between classes. Two other common inter-class relationships are "has-a" and "is-implemented-in-terms-of." These relationships are considered in Items 38 and 39. It's not uncommon for C++ designs to go awry because one of these other important relationships was incorrectly modeled as is-a, so you should make sure that you understand the differences among these relationships and that you know how each is best modeled in C++.

Things to Remember

  • Public inheritance means "is-a." Everything that applies to base classes must also apply to derived classes, because every derived class object is a base class object.

Категории