I used to study C++ for a while, but never found a suitable project to get familiar with it. So I am learning C++ following an open source project on github, address: github
/* * Virtual Inheritance * Concept: Solves the data inconsistency problem caused by different copies of the same data member inherited from different paths in memory. * Set the common base class as a virtual base class. * At this time, the data members with the same name inherited from different paths have only one copy in memory, and the same function name has only one mapping. * Solves problems: * Solved the ambiguity problem, also saved memory, avoided data inconsistency problems. * * Analysis: * It can be seen from the program that the different inheritance types of C, D, E are three types: public A, virtual A and virtual B, where virtual B is used twice. * The second inheritance will directly reference the first copy, so we will see the output for the C, D parts on the console as B-A-A, where the second B is omitted. * According to the principle of inheritance, first base class, generating C-D, then member A, finally E, so the order is: B-A-A-C-D-A-E * */ # include<iostream>
classA{ int a; public: A(int x){ a =x; cout<<"virtual Base A .. "<<a<<endl; } }; classB:virtualpublic A{ public: B(int x):A(x){ cout<<"virtual Base B .. "<<x<<endl; } };
classC:virtualpublic A{ int x; public: C(int x){ cout<<"Constructing C .. "<<x<<endl; } };
classABC: public B, public C{ public: ABC(int i,int j,int k):C(i),B(j),A(k){ /* * A must be initialized here because the initialization of virtual inheritance is performed by the final derived class. * Since ABC is the final derived class of A's virtual inheritance, A needs to be initialized during initialization. */ cout<<"Constructing ABC .. "<<endl; } };
voidmain(){ ABC obj(1,2,3); system("pause"); }
The final derivation of the virtual base class will parse the constructor function (including no-parameter, no-parameter and default functions). If we add a no-parameter constructor to A and omit C, no error will be reported.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classA{ int a; public: A(){} A(int x){ a =x; cout<<"virtual Base A .. "<<a<<endl; } }; classC:virtualpublic A{ int x; public: C(int x){ cout<<"Constructing C .. "<<x<<endl; } };