Many C + + programmers never use private inheritance to design their classes. Indeed, if it is a place where private inheritance is used, it has no effect on the implementation of the function of the program. But this misuse is a dislocation of the description, it will cause the misunderstanding of readers, and even cause the users of the class is dazed. When we write a declaration of a class, we are actually doing an intent design. What designers need is precisely the exact description.
- The implication of private inheritance
To explain private inheritance, let's take a look at common inheritance to make a comparison.
Public inheritance is essentially a is-a relationship. For example, the description of a Jeep is a vehicle, then the following designs can be made:
Class Car{};class Jeep:public car{}
Private inheritance, subclasses can only be
class InternalUse the functionality of the parent class instead of opening the function of the parent class to the outside in the form of an interface, i.e.,
the object of the child classThe function interface to the parent class cannot be used directly. Therefore, the implication of private inheritance is as follows:
subclasses can use the functionality of the parent class to implement their own functionality。 This is the typical
has-aThe relationship.
Class Engine{public: void Run ();}; Class car:private engine{public: void Drive () { //Let Engine go! Run (); }};
On the relationship description, it is equivalent to a combination, such as:
Class car{... private: Engine m_engine;}
- Private Inheritance vs Combination
Private inheritance brings too much program overhead, but the combination is fast track approach, so in general, designers want to describe the relationship between has-a, the combination is preferred .
However, the following two methods must use private inheritance:
- Class A needs to use the protected member function of Class B to implement its own functionality.
- When a class needs to rewrite a virtual function of Class B
Talk about C + + private inheritance