1

I'm using vs2013(Win32) testing the following program:

#include <iostream>

class A {
    virtual void funA();
};

class B {
    virtual void funB();
};

class C :public A{
    int i;
    virtual void funC();
};

class D :public B, C{
    virtual void funD();
};

int main(){
    std::cout << "size A " << sizeof(A) << std::endl;
    std::cout << "size B " << sizeof(B) << std::endl;
    std::cout << "size C " << sizeof(C) << std::endl;
    std::cout << "size D " << sizeof(D) << std::endl;
    return 0;
}

And the result is

size A 4
size B 4
size C 8
size D 12

Why sizeof(C) != 8 + sizeof(A), and sizeof(D) != 4 + sizeof(B) + sizeof(C)?

Yuan Wen
  • 1,583
  • 3
  • 20
  • 38

1 Answers1

6

A is a single base class with virtual methods, hence a single vtable pointer, hence 4 bytes on a 32-bit platform like yours.

B is just like A.

C is just like A plus one 4-byte integer. Note that it still only has a single base class (A) which means still just one vtable pointer.

D inherits from two base classes with virtual methods which are not related to each other, hence D gets two vtable pointers (one for each base class), plus the 4-byte integer from C. Hence 12 bytes total.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • @YuanWen They don't need to, they only need larger tables. – molbdnilo Apr 19 '16 at 07:55
  • @YuanWen, vtable pointer is used to determine which virtual method to use on particular instance (whether it is instance of base or one of derived classes). – Andrei R. Apr 19 '16 at 07:56
  • For C,it only has one vtable ptr,and I think the vtable includes funA and funC.For D,it has two vtable ptr,then,where can I find funD?@AndreiR.@molbdnilo – Yuan Wen Apr 19 '16 at 08:25
  • 1
    @YuanWen: A singly derived class object can point to a single vtable which includes the base methods and also any virtual methods in the derived class. That is, the derived methods inhabit the space already required by the base class methods. Your `class D` inherits from two bases, and the most likely implementation is that it will store its derived class methods in the first of its two vtables. You can see a diagram and more text exploring this here: http://stackoverflow.com/questions/15921372/c-virtual-table-layout-of-mimultiple-inheritance – John Zwinck Apr 19 '16 at 11:33