Recently in the inheritance of C + +, diamond inheritance is more difficult to understand the part, so through the review of the material after the idea, but also shared with the students on the diamond virtual inheritance of some things.
Diamond inheritance is not used in general, but by understanding diamond inheritance, we can see how the compiler works.
First, diamond virtual inheritance is the two base class that inherits a common superclass, and then two base classes that have a common derived class.
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7D/3E/wKioL1bjlHujLuXsAAALr0cNA0k826.png "title=" Diamond Inheritance " alt= "Wkiol1bjlhujluxsaaalr0cna0k826.png"/>
Class base{public: void func () { cout << "Base::func" <<endl; }public : int a;}; class base1:virtual public base{public : virtual void Func1 () { cout<< "Base1::func1" &NBSP;<<ENDL;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;VIRTUAL&NBSP;VOID&NBSP;FUNC2 () { cout<< "Base1::func2" <<endl; }public : int b1 ;}; class base2:virtual public base{public : virtual void Func1 () { cout<< "Base2::func1" <<endl;&nbSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;VIRTUAL&NBSP;VOID&NBSP;FUNC2 () { cout<< "Base2::func2" <<endl; }public : int b2 ;}; class derive : public base1, public base2{public : VIRTUAL&NBSP;VOID&NBSP;FUNC1 () { cout << "Derive::func1" <<endl; } virtual void &NBSP;FUNC3 () { cout<< "Derive:: Func3 " <<endl; }pubilc : int d1 ;};
In this we construct a derive object D, call the Watch window and see how the compiler is stored.
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7D/3F/wKiom1bjmfChUB_rAAA_pbwY8X8420.png "title=" Capture 2. PNG "alt=" Wkiom1bjmfchub_raaa_pbwy8x8420.png "/>
As we can see, there is a virtual function table pointer in both BASE1 and Base2, and the compiler solves the two semantic problem with the virtual function table pointer, and the virtual function table pointer addresses of BASE1 and Base2 are different, so they all have their own virtual tables.
int main () {//test1 (); Derive D; D.A = 1; D.B1 = 2; D.B2 = 3; D.D1 = 4; return 0;}
Before the data members of the class I was set to public, convenient to assign the value to directly recall memory changes in memory. Then assign a value to the data member A,b1,b2,d and then bring up the memory to see:
650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7D/3F/wKioL1bjriHR4X2ZAAA9VfsEPMM399.png "title=" Capture 4. PNG "alt=" Wkiol1bjrihr4x2zaaa9vfsepmm399.png "/>
So the essence of virtual inheritance is to solve the ambiguity of data by using a virtual base class pointer and a virtual function table pointer.
Diamond Virtual Inheritance