Private Inheritance

A seldom-used technique in CeePlusPlus where a class can inherit from another class, without creating a subtype.

The normal way of expressing inheritance in C++ is

 class Derived: public Base {
     // stuff
 };

When this is done, Derived is a subtype of Base, and anywhere one encounters a Base * or Base & one can substitute a Derived */Derived &. (But be careful of ObjectSlicing in C++)

To get private inheritance, one does:

 class Derived: private Base { // private keyword is actually optional
    //stuff
 };

Interestingly enough, private inheritance is the default type of inheritance for classes but not for structs--ie if you omit the "public" keyword in the inheritance specification, you get private inheritance.

Consequences of private inheritance:

In most cases, you're better off with composition rather than private inheritance. If private inheritance broke the subtype link but didn't make all the members private, it might be more useful as SyntacticSugar--but since it does make members private, it isn't very good at cloning an implementation while avoiding subtyping--which is what you need when you do ImplementationInheritance.

In 8 years of professional C++ programming, I cannot recall a single instance of my using private inheritance.


It should be noted that C++ also has protected inheritance--replace public/private with "protected" in the examples above. Just like private inheritance, except that things public in the base class become protected in the subclass; things protected or private in the base class are unchanged in the subclass. Probably even less useful than PrivateInheritance.

Right, but 'protected:' declarations are useful in base classes and appear all the time. Perhaps this is what protected inheritance should really be doing: making 'private' declarations behave like protected ones in derived classes, instead of making 'public' declarations act like 'private' ones. Does TheDesignAndEvolutionOfCeePlusPlus? cover the historical reasons for protected inheritance?

The protected keyword itself is useful in several contexts:

Regarding protected inheritance--C++ never allows a derived class to grant access to a base classes private members; the notion of protected inheritance meaning "make private things protected" would violate that principle.


Writer Abdul Majid Sr. Programmer Malakand Agency


CategoryCpp

EditText of this page (last edited June 24, 2013) or FindPage with title or text search