In OOP, inheritance is the mechanism which allows a code module (commonly called a class) to take on the characteristics of a parent module, redefine some and add to them. Inheritance is necessary due to the Open Closed Principle.

Private inheritance refers to the access control on the inherited features - with private inheritance, the features of the base class are not available to the rest of the program to access.

Private inheritance is not used to model "isa" relationships. If a base class Animal has a derived class Elephant, then Elephant is not an Animal, and cannot be treated as one. Because the features of the base class cannot be accessed by the rest of the program when you use private inheritance, an attempt by the rest of the program to call one of Animal's member functions on an Elephant object will fail. Use public inheritance to model "isa" relationships.

Private inheritance is used to model "is-implemented-in-terms-of" relationships (an alternative is layering). How do you pick between the two? The general rule is "Use layering when you can, use private inheritance when you have to."

As the OOP savant you are, you'll want to use private inheritance so as not to violate the Interface Segregation Principle, which states that interfaces should be minimal and specialised (see the node on the principle for the reasoning behind this).

If you create a generalised class then you can have specialised interface classes that have a private inheritance relationship to the base class. If you declare the base class members as protected (only accessible to derived classes), then you send the message to your client that the base class is unsuitable for use apart from via interface classes. These interface classes can perform their own specialised tasks and use the base implementation.

Bertrand Meyer would be proud.

More

Log in or register to write something here or to contact authors.