• Tidak ada hasil yang ditemukan

Make sure public inheritance models “is-a.”

Dalam dokumen Book Praise for Effective C++, Third Edition (Halaman 171-177)

ptg7544714

ptg7544714 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 inher- itance 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 pen- guins 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

ptg7544714 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 soft- ware 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 dis- tinction 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” prob- lem. That is to redefine the fly function for penguins so that it gener- ates 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!"); } ...

};

ptg7544714 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 com- pilers, 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, com- pilers 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 compila- tion to the one that detects them only at runtime.

Perhaps you’ll concede that your ornithological intuition may be lack- ing, 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?

Square Rectangle

?

ptg7544714

“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 asser- tions?

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

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

ptg7544714

After returning from makeBigger, s’s height is again the same as its width. (Note that s is passed to makeBigger by reference, so make- Bigger 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 mathe- matics — 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 inherit- ance asserts that everything that applies to base class objects — everything! — also applies to derived class objects. In the case of rect- angles 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 oth- ers), 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 Rect- angle 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.

ptg7544714

Dalam dokumen Book Praise for Effective C++, Third Edition (Halaman 171-177)

Dokumen terkait