I am trying to uncover some low level things with virtual table and inheritance.
When you create a new class, inheriting two classes and adding new virtual functions, where exactly is vptr stored?
It seems to me that in this case the compiler performs some "vptr optimization". And I'm trying to figure it out.
Suppose we have the following structures:
struct A { int a; virtual void fa(); }; struct B { double b; virtual void fb(); }; struct C : A, B { char c; virtual void fa(); virtual void fb(); virtual void fc(); };
In the case of x86 and align = 4, A and B in memory will look like this:
+
But when I try to build C , I get the following:
+------+------+------+------+------+------+------+ C: | vptr | a | vptr | b | c | +------+------+------+------+------+------+------+ but sizeof(C) = 32 ; (C*)&c; // 0x100 (B*)&c; // 0x108 (A*)&c; // 0x100 &c.a; // 0x104 &c.b; // 0x110 &c.c; // 0x118
So where is vptr C ? I can assume that the compiler joins different virtual tables (e.g. vptr from A and C ), but in this case, why sizeof(C) returns sizeof(A) + sizeof(B) + sizeof(alligned_char) + sizeof (vptr)
struct D : public C {} has the same story - no vptr D
I am using the msvc 2012 x86 compiler.
source share