There are two separate things here that cause extra overhead.
Firstly, having virtual functions in the base class increases its size by a pointer size (4 bytes in this case), because it needs to store the pointer to the virtual method table:
normal inheritance with virtual functions:
0 4 8 12
| base |
| vfptr | i | j |
Secondly, in virtual inheritance extra information is needed in derived
to be able to locate base
. In normal inheritance the offset between derived
and base
is a compile time constant (0 for single inheritance). In virtual inheritance the offset can depend on the runtime type and actual type hierarchy of the object. Implementations may vary, but for example Visual C++ does it something like this:
virtual inheritance with virtual functions:
0 4 8 12 16
| base |
| xxx | j | vfptr | i |
Where xxx
is a pointer to some type information record, that allows to determine the offset to base
.
And of course it's possible to have virtual inheritance without virtual functions:
virtual inheritance without virtual functions:
0 4 8 12
| base |
| xxx | j | i |
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…