How the compilers implement the virtual inheritance?
In the following code:
class A {
public:
A(int) {}
};
class B : public virtual A {
publ
The compiler does not create another constructor of B - but it ignores the A(1)
. Since A
is virtually inherited, it is constructed first, with its default constructor. And since it's already constructed when B()
is invoked, the A(1)
part is ignored.
Edit - I missed the A(3)
part in C
's constructor initialization list. When virtual inheritance is used, only the most derived class initializes the virtual base classes. So A
will be constructed with A(3)
and not its default constructor. The rest still stands - any initializations of A
by an intermediate class (here B
) are ignored.
Edit 2, trying to answer the actual question regarding the implementation of the above:
In Visual Studio (at least 2010), a flag is used instead of having two implementations of B()
. Since B
virtually inherits from A
, before it calls A
's constructor, the flag is checked. If the flag is not set, the call to A()
is skipped. Then, in every class deriving from B
, the flag is reset after it initializes A
. The same mechanism is used to prevent C
from initializing A
if it's part of some D
(if D
inherits from C
, D
will initialize A
).