The difference between protected and private inheritance in C++ inheritance

Let's review inheritance first. Inheritance is a way to improve code utilization and reduce duplication.

First of all, there are two classes, one is called the parent class, the other is called the subclass, the parent is also called the base class, and the subclass is also called the derived class, because the subclass uses the same member functions or member data as the parent class, for example , The parent class is the primate, the child class is the orangutan, humans... They all have the same member data, such as leg length, height, waist circumference... In order to make the code more concise, that is, to avoid duplication, we need to use inheritance.

Next, look at the way of inheritance. Inheritance is divided into three types: public, protected, and private. In fact, when the child class gets the members of the parent class (including member data and member functions), the member permissions change. First of all, we need to know the parent Private members of a class cannot be inherited . Public inheritance permissions remain unchanged, protected inheritance public permissions and protection permissions all become protected permissions, and private inheritance subclass inherited permissions all become private permissions.

Outside the class, neither the protected permissions nor the private permissions can be accessed. Both need an interface. However, the protected permissions can continue to be inherited, that is, it can be inherited by the son. If the son is inherited in the public or protected mode, the grandson can also inherit the son... , The father passes the son, the son passes the grandson, the sons and the sons are endless...

However, note that if the parent class is a member of private permissions, the child class cannot inherit it; or, if the parent class has public permissions, but the child class inherits privately, then the grandchildren also cannot inherit.

Guess you like

Origin blog.csdn.net/myf_666/article/details/114106333