In the following code, I tried to create a Leaf obj object to see the constructor order in multi-layer inheritance, but I find the obj structure and constructor calls in this case a little strange.
#include<iostream> using namespace std; class Base1 { public: Base1(void) { cout << "class Base1" << endl; } }; class Base2 { public: Base2(void) { cout << "class Base2" << endl; } }; class Level1 : public Base2, virtual public Base1 { public: Level1(void) { cout << "class Level1" << endl; } }; class Level2 : public Base2, virtual public Base1 { public: Level2(void) { cout << "class Level2" << endl; } }; class Leaf :virtual public Level2, virtual public Level1 { public: Leaf(void) { cout << "class Leaf" << endl; } }; int main(void) { Leaf obj; return 0; }
With an output displaying constructor calls:
class Base1 class Base2 clase Level2 class Base2 class Level1 class Leaf
But the obj structure at the end of the program is actually:
obj --Level2 ----Base2 ----Base1 --Level1 ----Base2 ----Base1 --Base1
I know that Base1 of obj is virtual inherited, but when building obj it is also necessary to build Level2 and Level1 , which leads to Base1 in each of its members. But the whole build process only calls the Base1 constructor once. I can not explain it. Does this mean that Base1 in Level2 and Level1 inside obj shares the same data with Base1 , which directly belongs to obj ?
source share