How an object in C/C++ is stored

No Inheritance
  1. class A
  2. {
  3. public:
  4.     int a;
  5. };
  6.  
  7. class B
  8. {
  9. public:
  10.     int b;
  11. };
  12.  
  13. class C: public A, public B
  14. {
  15. public:
  16.     int c;
  17. };
  18.  
  19. void main()
  20. {
  21.     C obj;
  22.     cout << &obj << endl << &obj.a << endl << &obj.b << endl << &obj.c << endl;
  23. }
Output:
0012FF58
0012FF58
0012FF5C
0012FF60
if change the order of inheritance into: 


class C : public B, public A

the output is:

0012FF58
0012FF5C
0012FF58
0012FF60
  • The storage of a derived class is dependent on the declare order.
Single Inheritance

In the case that a virtual function is added to A:
  1. class A
  2. {
  3. public:
  4.     int a;
  5. virtual void fA() {}
  6. };
  7. ...
  8. class C: public A, public B
  9. ...
Output:
0012FF54
0012FF58
0012FF5C
0012FF60
the new address of obj now is 0012FF54 instead of 0012FF58. First extra 4 bytes is used to for __vfptr. And one more thing, if I change the order of inheritance (don't remove the virtual function in A), the output does not change (!!!).
  • It seems that in the multiple inheritance case, the class which contains virtual methodhas higher priority when being storaged.
Multiple Inheritance

Next, add a new virtual method to B and change to order of inheritance in turn, a C object now will contain two __vfptr corresponding with the A and B (or B and A up to the declaration order).
Output:
0012FF50
0012FF54
0012FF5C
0012FF60
  • The number of __vfptrs which an object contains are up to the number of classes it inherits.
(To be continued ... )