The significance of private inheritance lies in "be implemented in turns ".
Private inheritance and public inheritance are completely different, mainly reflected in two places
First, the public inherits the permission of the parent class in the subclass, that is, the member function or member in the parent class is public, and the variable is still public in the subclass, this is also true for private or protected member functions or member variables, but private inheritance does not. It destroys the access permission calibration of the parent class red and converts it to private, this does not affect the province of the subclass, but affects the Subclass. The subclass of the subclass will not be able to access these member variables or member functions declared/defined in the grandfathers class.
Second, the Liskov rule is no longer used, that is, the rule "all parent classes can be replaced by quilt classes" is not valid in private.
# Include <iostream> using namespace std; class Person {}; class Student: private Person {}; void eat (const Person & p) {} int main () {Person p; student s; eat (p); // OK eat (s); // false}
However, if Student inherits Person from the public, the compiler will not report an error. This is exactly the embodiment of the alternative principle of Liskov in private inheritance.
Private inheritance is rarely used unless there are some wonderful design requirements.
Class TypeDefine {}; class SimpleClass {int a; TypeDefine obj ;}; class SimpleDerivedClass: private TypeDefine {int a ;}; int main () {cout <sizeof (TypeDefine) <endl; cout <sizeof (SimpleClass) <endl; cout <sizeof (SimpleDerivedClass) <endl ;}
The first class is an empty class. It is just a blank name. It seems to be empty, but it is not like this. For an empty class, the compiler will generate the default function: default constructor, default copy constructor, default destructor, default value assignment operator. Although the function does not occupy space, every object of the class must have a unique memory address, therefore, the value calculated by sizeof the empty class is 1. non-empty classes because they already have member variables, the compiler can use these member variables to differentiate memory addresses, thus representing different objects of the class.
The second output is 8, int 4 bytes and then added to the four bytes of the empty class object. Theoretically, the compiler will perform a memory alignment operation, so that the class object size is an integer multiple of the processing word length
The third output time is 4, which is actually a blank base class optimization by the compiler. It was originally intended to insert a byte for the blank class object, but because the subclass already has an object, in theory, this object can be used to identify different classes of the same class. Therefore, the compiler will no longer insert bytes.
This result is the benefit of private inheritance.
Wise and prudent use of private inheritance