#686 – Inheritance vs. Containment

You can think of inheritance as white box reuse of existing code, meaning that a derived class can see some aspects of the internals of the base class.  This violates the principle of encapsulation, which states that the implementation details of a class are hidden from any code that uses the class.

There is another method of code reuse known as containment, which results in black box reuse of existing code.  Instead of deriving from a base class, the new class just creates an instance of the class internally and accesses only the public members of the instance.  The instance of the base class can be thought of as a black box, because the derived class doesn’t have access to the implementation details of the base class.

Advertisement