When a virtual table is involved in C + +, the layout of the class object is divided into: virtual table and data member, subclass contains derived class layout, assume the following program:
1#include <iostream>2 3 using namespacestd;4 5 classB {6 Private:7 intA;8 Public:9 B () {TenA = One; One } A - Virtual voidFun () { -cout <<"B::fun"<<Endl; the } - }; - - classA: PublicB { + Public: - A () { +cout <<"class A Constructor"<<Endl; Am =3; atn =2; - } - -~A () { -cout <<"~a ()"<<Endl; - } in Virtual voidFun () { -cout <<"A::fun"<<Endl; to } + - Private: the intM,n; * }; $ Panax Notoginseng intMainintargcChar*argv[]) - { the A; + int*p; Atypedefvoid(*pf_t) (void); the + pf_t PF; -p = static_cast<int*> ((int*) &a); $PF =(pf_t) p; $ - int*vptr = * (int* *) &A; - int*vtable = (int*)*vptr; thePF = (pf_t) vtable[2]; - Wuyiprintf"address A::fun%p\n", pf); the -cout <<"P:"<< *p <<Endl; WuP + + ; -cout <<"P:"<< *p <<Endl; Aboutp++; $cout <<"P:"<< *p <<Endl; -p++; -cout <<"P:"<< *p <<Endl; - Ap++; +cout <<"P:"<< *p <<Endl; the - $ return 0; the}
With the VS 2010 Display Object Layout diagram (cl-d1reportallclasslayout), where meta is the type information for the corresponding object:
Class B:
1 class B Size (8): 2 +--- 3 0 | {VFPTR} 4 4 | a 5 +--- 6 7b::[email protected]: 8 | &B_meta 9 | 0 Ten 0 | &b::fun
Class A:
class A size (16 ): +--- | +---(base class B) 0 | | {vfptr} 4 | | a | +---8 | M 12 | n +---a::[email protected]: | &a_meta | 0 0 | &a::funa::fun 0
Object Layout in C + +