Non-public Inheritance in C++
Parent classes are usually listed using the public
keyword. You may be wondering if a parent can be private
or protected
. In fact, it can, though neither is as common as public
.
If you don't specify any access specifier for the parent, then it is private
inheritance for a class, and public
inheritance for a struct
.
Declaring the relationship with the parent to be protected
means that all public and protected member functions and data members from the base class become protected in the context of the derived class. Similarly, specifying private
inheritance means that all public and protected member functions and data members of the base class become private in the derived class. (Private members in the parent class remain parents and thus inaccessible.)
There are a handful of reasons why you might want to uniformly degrade the access level of the parent in this way, but most reasons imply flaws in the design of the hierarchy. Some programmers abuse this language feature, often in combination with multiple inheritance, to implement components
of a class. Instead of making an Airplane
class that contains an Engine
data member and a Fuselage
data member, they make an Airplane
class that is a protected Engine
and a protected Fuselage
. In this way, the Airplane doesn't look like an engine or a fuselage to client code (because everything is protected), but it is able to use all of that functionality internally.