KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have some questions about the object size with virtual. 1) virtual function class A { public: int a; virtual void v(); } The size of class A is 8bytes....one integer(4 bytes) plus one virtual pointer(4 bytes) It's clear! class B: public A{ public: int b; virtual void w(); } What's the size of class B? I tested using sizeof B, it prints 12 Does it mean that only one vptr is there even both of class B and class A have virtual function? Why there is only one vptr? class A { public: int a; virtual void v(); }; class B { public: int b; virtual void w(); }; class C : public A, public B { public: int c; virtual void x(); }; The sizeof C is 20........ It seems that in this case, two vptrs are in the layout.....How does this happen? I think the two vptrs one is for class A and another is for class B....so there is no vptr for the virtual function of class C? My question is, what's the rule about the number of vptrs in inheritance? 2) virtual inheritance class A { public: int a; virtual void v(); }; class B: virtual public A{ //virtual inheritance public: int b; virtual void w(); }; class C : public A { //non-virtual inheritance public: int c; virtual void x(); }; class D: public B, public C { public: int d; virtual void y(); }; The sizeof A is 8 bytes -------------- 4(int a) + 4 (vptr) = 8 The sizeof B is 16 bytes -------------- Without virtual it should be 4 + 4 + 4 = 12. why there is another 4 bytes here? What's the layout of class B ? The sizeof C is 12 bytes. -------------- 4 + 4 + 4 = 12. It's clear! The sizeof D is 32 bytes -------
Tags (comma-separated)
Save Edits
Cancel