Virtual inheritance
Memory layout: Base1,base2 each has its own virtual table, because its own virtual function in the class.
#include <iostream>using namespace std;typedef void (*fun) (); class base{public:virtual &NBSP;VOID&NBSP;FUN1 () {cout << "base::fun1 ()" &NBSP;<<&NBSP;ENDL;} public:int _b;}; CLASS&NBSP;BASE1&NBSP;:VIRTUAL&NBSP;PUBLIC&NBSP;BASE{PUBLIC:VIRTUAL&NBSP;VOID&NBSP;FUN1 () {cout << "base1::fun1 ()" &NBSP;<<&NBSP;ENDL;} VIRTUAL&NBSP;VOID&NBSP;FUN3 () {}public:int _b1;}; CLASS&NBSP;BASE2&NBSP;:VIRTUAL&NBSP;PUBLIC&NBSP;BASE{PUBLIC:VIRTUAL&NBSP;VOID&NBSP;FUN1 () {cout << "base2::fun1 ()" &NBSP;<<&NBSP;ENDL;} Virtual void fun2 () {}public:int _b2;}; class derive :p ublic base1, public base2{public:virtual void fun1 () {cout << "derive::fun1 ()" &NBSP;<<&NBSP;ENDL;} public:int _d;}; Void printvtable (int *ptr) {for (int i = 0; ptr[i] != 0; ++i) {fun f = (Fun) ptr[i];f ();}} Int main () {DERIVE&NBsp;b1;b1._b1 = 2;b1. Base1::_b = 1;b1._b2 = 3;b1._d = 4;/*int *p1= (int *) (* (int*) &B1); Printvtable (p1), cout<<sizeof (BASE1) <<endl;int *p2= (int*) (* (int*) ((int) &b1+sizeof (BASE1))) ; Printvtable (p2); */system ("pause"); return 0;}
650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/77/A8/wKioL1ZqodbiFuuKAAAsuVkV5BI474.png "title=" QQ picture 20151211175828.png "alt=" Wkiol1zqodbifuukaaasuvkv5bi474.png "/>
2. There is a virtual function in the subclass, so the virtual table pointer must be created in the parent class
Class Base1:virtual Public Base
{
Public
virtual void fun1 ()
{
cout << "base1::fun1 ()" << Endl;
}
Public
int _b1;
};
Class Base2:virtual Public Base
{
Public
virtual void fun1 ()
{
cout << "base2::fun1 ()" << Endl;
}
Public
int _b2;
};
Class Derive:p ublic Base1, public Base2
{
Public
virtual void fun1 ()
{
cout << "derive::fun1 ()" << Endl;
}
virtual void fun2 ()
{
}
Public
int _d;
};
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/77/A8/wKioL1Zqo_SD5vCWAAAjGUdgBa4988.png "title=" Untitled. png "alt=" Wkiol1zqo_sd5vcwaaajgudgba4988.png "/>
3. No virtual function in parent class, create virtual table pointer in child class
Class Base
{
Public
Public
int _b;
};
Class Base1:virtual Public Base
{
Public
virtual void fun1 ()
{
cout << "base1::fun1 ()" << Endl;
}
Public
int _b1;
};
Class Base2:virtual Public Base
{
Public
virtual void fun1 ()
{
cout << "base2::fun1 ()" << Endl;
}
Public
int _b2;
};
Class Derive:p ublic Base1, public Base2
{
Public
virtual void fun1 ()
{
cout << "derive::fun1 ()" << Endl;
}
virtual void fun2 ()
{
}
Public
int _d;
};
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/77/A9/wKiom1ZqpPTR2ZmpAAAX85Ab32c278.png "title=" Untitled. png "alt=" Wkiom1zqpptr2zmpaaax85ab32c278.png "/>
This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1722157
Various inherited memory layouts (virtual tables)