In the previous article, we discussed the object memory layout of C + + single general inheritance http://www.cnblogs.com/uangyy/p/4621561.html
Next, we continue to discuss the second scenario:
2. Single virtual inheritance: There are member variables, with virtual and virtual functions of the overlay, dummy inheritance.
Let's assume that one of the following inheritance relationships
The source code is as follows:
#include <iostream>using namespacestd;classparent{ Public: intiparent; Parent (): Iparent (Ten) {} Virtual voidf () {cout<<"parent::f ()"<<Endl; } Virtual voidg () {cout<<"parent::g ()"<<Endl; }};classChild:Virtual Publicparent{ Public: intichild; Child (): Ichild ( -) {} Virtual voidf () {cout<<"child::f ()"<<Endl; } Virtual voidG_child () {cout<<"Child::g_child ()"<<Endl; }};intMainintargcChar**argv) {Child C; typedefvoid(*fun) (void); Fun PF; cout<<"[0] child::vfptr->"<<Endl; cout<<"[0]"; PF= (Fun) * ((int*)*(int*) &c +0); PF (); cout<<"[0] 0x"<< (Fun) * ((int*)*(int*) &c +1) <<Endl; cout<<"[1] child::vbptr->"<<Endl; cout<<"[0]"<< * ((int*)*((int*) &c +1) +0) <<Endl; cout<<"[1]"<< * ((int*)*((int*) &c +1) +1) <<Endl; cout<<"[2]"<< * ((int*)*((int*) &c +1) +2) <<Endl; cout<<"[2] child.ichild ="<< (int)*((int*) &c +2) <<Endl; cout<<"[3] = 0x"<< (int*)*((int*) &c +3) <<Endl; cout<<"[4] parent::vfptr->"<<Endl; cout<<"[0]"; PF= (Fun) * ((int*)*((int*) &c +4) +0); PF (); cout<<"[1]"; PF= (Fun) * ((int*)*((int*) &c +4) +1); PF (); cout<<"[2] 0x"<< (Fun) * ((int*)*((int*) &c +4) +2) <<Endl; cout<<"[5] parent.iparent ="<< (int)*((int*) &c +5) <<Endl; return 0;}
The result of the code operation is as follows:
[0] Child::vfptr-> [0] Child::g_child () [0]0x00000000[1] Child::vbptr-> [0] -4 [1] A [2]0[2] Child.ichild = -[3] =0x00000000[4] Parent::vfptr-> [0] Child::f () [1] Parent::g () [2]0x00000000[5] Parent.iparent =Ten
Here is the memory layout of the object:
By us we can know:
1. Under the virtual inheritance relationship, the object of the derived class produces a pointer to the virtual base class table Pointer Vbptr, which holds the offset address of the base class in the object (starting from 1, the 0 cell is not known what is used)
2. In this relationship first, the inherited base class is placed on the last side, first of all the member variables and the virtual function table of the derived class
3. The order of deposit is: derived class virtual function table pointer, virtual base class table pointer-------a member variable of a derived class, NULL----base class virtual function table pointer--base class member variable
sizeof (c) = 24:2 * sizeof (VFPTR) + 2 * sizeof (int) + sizeof (VBPTR) + sizeof (void *)
Note: 1. Under the inheritance relationship of virtual machine city, the object of the derived class will have a virtual base class table pointer, occupying 4 bytes;
2. There is a null pointer between the derived class and the base class that is inherited by the virtual.
C + + Object memory layout (ii)