The role of private inheritance in C++

  • 2020-05-30 20:55:06
  • OfStack

The role of private inheritance in C++

Privately inherited

Rule 1: in contrast to public inheritance, compiler 1 generally does not convert derived class objects into base class objects if the inheritance relationship between two classes is private.

Rule 2: members inherited from a private base class become private members of a derived class, even if they are protected or public members in the base class.

The meaning of private inheritance: private inheritance means "to use... To make it happen."

If you make class D private inherit from class B, you do so because you want to take advantage of some code that already exists in class B, not because of any conceptual relationship between objects of type B and objects of type D.

Thus, private inheritance is purely an implementation technique.

Private inheritance means just inheriting the implementation and the interface is ignored. If D inherits privately from B, then D objects use B objects in their implementation, and that's it.
Private inheritance is meaningless in the software "design" process, but only useful in the software "implementation".

1. Declaration form of private inheritance:

  class  Foo  :  private  Bar 
           void  fun(); 
     //  ... 

Public and protected members of a base class become private members of a derived class; The inheritance belongs to part 1 of the is-a relationship, while the private inheritance belongs to part 1 of the has-a relationship

2. Architecturally, private inheritance represents an 'has a 'relationship, but differs from aggregation in the following ways:

Private inheritance forms can introduce unnecessary multiple inheritance

The private inheritance form allows access to the protected (protected) members of the base class

Private inheritance allows derived classes to override virtual functions of base classes (polymorphic)

3. Use combinations whenever possible, and use private inheritance only as a last resort

Usually you don't want to access the internals of other classes, and private inheritance gives you such privileges (and responsibilities). But private inheritance is not harmful. It's just that it increases the likelihood that someone will change something and break your code, making it more expensive to maintain.

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!

Related articles: