Read this code
class Top { protected: int x; public: Top(int n):x(n){cout<<"Top"<<endl;} virtual ~Top(){} }; class Left:virtual public Top { protected: int y; public: Left(int m,int n):Top(m){y=n;cout<<"Left"<<endl;} }; class Right:public virtual Top { protected: int z; public: Right(int m,int n):Top(m){z=n;cout<<"Right"<<endl;} }; class Bottom:public Left,public Right { int w; public: Bottom(int i,int j,int k,int m):Top(i),Left(i,j),Right(i,k),w(m) { cout<<"Bottom"<<endl; } }; int main() { Bottom b(1,2,3,4); cout<<"sizeof(b) "<<sizeof(b)<<","<<sizeof(Bottom)<<endl; cout<<sizeof(Left)<<","<<sizeof(Right)<<","<<sizeof(Top)<<endl; for(int i=0;i<sizeof(b);i+=4) cout<<*(reinterpret_cast<int*>((&b)+i))<<"________"<<endl; system("PAUSE"); }
The result is as follows:
Top
Left
Right
Bottom
Sizeof (B) 28
16, 16, 8
4657244 ________
2367460 ________
0 ________
746 ________
44 ________
5701724 ________
4 ________
Press any key to continue...
That is to say, top occupies 8 bytes, which is easy to understand.
Int X; // 4 bytes
Virtual ~ Top () {}// virtual table entry of the base class, 4 bytes
Next, we can see that both left and right are 16 bytes.
In addition to the top 8 bytes, only int y is in left; 4 bytes, where are 4 bytes?
Because it is virtual inheritance, the subclass of virtual inheritance must contain a pointer to the base class to achieve dynamic Association.
An additional 4 bytes of space is required. Therefore, the total size is 8 + 4 + 4 = 16 bytes.
Right.
Let's look at how the bottom size is 28 bytes?
Virtual inheritance is a pyramid inheritance. The base class size is 8 bytes.
While bottom is a common multi-inheritance, therefore, the size of the bottom should be the bottom part + left part + right part + pointer to the base class + base class size (Virtual inheritance leads to only one base class instance ).
Top
//
//
Left right
//
//
Bottom
Now, the base class 8 bytes + left4 bytes + right4 bytes + 4 bytes refer to the base class pointer * 2 + bottom4 bytes = 28 bytes.
For more information about functions and whether variables are included in the sizeof instance, see the previous two articles.
We recommend that you use your own derivation based on your own data.