c++ - How much space does a Derived class cost?If itself and its base class both have virtual methods? -
i'm using vs2013(win32) testing following program:
#include <iostream> class { 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 " << 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 result
size 4
size b 4
size c 8
size d 12
why sizeof(c) != 8 + sizeof(a), , sizeof(d) != 4 + sizeof(b) + sizeof(c)?
a
single base class virtual methods, hence single vtable pointer, hence 4 bytes on 32-bit platform yours.
b
a
.
c
a
plus 1 4-byte integer. note still has single base class (a
) means still 1 vtable pointer.
d
inherits 2 base classes virtual methods not related each other, hence d
gets 2 vtable
pointers (one each base class), plus 4-byte integer c
. hence 12 bytes total.
Comments
Post a Comment