Does using virtual inheritance in C++ have a runtime penalty in compiled code, when we call a regular function member from its base class? Sample code:
Yes, virtual inheritance has a run-time performance overhead. This is because the compiler, for any pointer/reference to object, cannot find it's sub-objects at compile-time. In constrast, for single inheritance, each sub-object is located at a static offset of the original object. Consider:
class A { ... };
class B : public A { ... }
The memory layout of B looks a little like this:
| B's stuff | A's stuff |
In this case, the compiler knows where A is. However, now consider the case of MVI.
class A { ... };
class B : public virtual A { ... };
class C : public virtual A { ... };
class D : public C, public B { ... };
B's memory layout:
| B's stuff | A's stuff |
C's memory layout:
| C's stuff | A's stuff |
But wait! When D is instantiated, it doesn't look like that.
| D's stuff | B's stuff | C's stuff | A's stuff |
Now, if you have a B*, if it really points to a B, then A is right next to the B- but if it points to a D, then in order to obtain A* you really need to skip over the C sub-object, and since any given B* could point to a B or a D dynamically at run-time, then you will need to alter the pointer dynamically. This, at the minimum, means that you will have to produce code to find that value by some means, as opposed to having the value baked-in at compile-time, which is what occurs for single inheritance.