Inheritance Breaks Encapsulation

It has been argued that InheritanceBreaksEncapsulation because the SuperClass? is not well encapsulated from the SubClass?:

Inheritance creates a tight coupling between base and derived classes. Whether or not that is good or bad depends on the nature of what you are trying to do; there are cases where delegation might be more appropriate, and there are cases where inheritance is GoodEnough.

Encapsulation and InformationHiding aren't absolutes, otherwise it would be a violation for the author of the code to lay eyes on any of the classes he writes.

So to avoid that reductio ad absurdum, one needs to drill down to see what purpose encapsulation is supposed to achieve, and then ask whether e.g. inheritance violates that purpose -- not whether it violates the superficial definition.

The class is not always the proper GranuleOfRelease

Especially if you make a lot of classes because you have classes with few responsibilities. Then they need to cooperate and they can cooperate at the friend level because they are written to work together. See TightGroupOfClasses.

Indeed, at least in C++ wise use of friend improves encapsulation.

And conversely, unwise use of "friend" makes encapsulation a lot worse. It's one of the many C++ two-edged swords. Often it's a way to simulate MultiMethods -- which perhaps goes to the heart of why classes aren't always the right unit.

Unwise anything is bad.

Sigh. That's not the point. The point is that "friend" is generally a bad thing. Its wise uses are very much in the minority.

The rest of the point is that it is a botched part of the design of C++; it wouldn't be necessary if MultiMethods had been in C++ in the first place.

View edit of May 11, 2005 or FindPage with title or text search