I'm trying to undestand some low-level things with virtual table and inheritance.
When you create new class by inheriting two classes and adding new virtual functions, where exactly the vptr will be stored?
It seems to me, that compiler performs some 'vptr-optimization' in that case. And I'm trying to figure it out.
Suppose, we have the following structs:
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 case of x86 and align=4, A
and B
in memory will look like this:
+------+------+
A: | vptr | a |
+------+------+
sizeof(A) = 4 + 4 = 8
+------+------+------+------+
B: | vptr | b |
+------+------+------+------+
sizeof(B) = 8 + 8 = 16
But when I try to reassemble C
, I get this:
+------+------+------+------+------+------+------+
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 the vptr of C
? I can suppose that compiler merge different virtual tables (ex. vptr of A
and C
), but in that case why sizeof(C)
returns sizeof(A)
+ sizeof(B)
+ sizeof(alligned_char)
+ sizeof(vptr)
The struct D : public C {}
has the same story - there is no vptr of D
.
The compiler I use is msvc 2012 x86.