In your setup as you have it, B
is not actually inherited virtually, because you would have to declare virtual inheritance for B
in both B1
and B2
(it always has to happen at the lowest level if the two "branches" are expected to be merged higher up in the class inheritance hierarchy), i.e.
class B1 : virtual public B
{
protected:
B1() : B(0){}
};
class B2 : virtual public B
{
protected:
B2() : B(10){}
};
If you do that, initialization of B
would be completely different, because there are special rules for the construction of virtual base classes:
In virtual inheritance, the virtual base class is always initialized by the most derived class. Thus, as you have implemented the constructor of D
as
D() : B1(), B2(){}
and therefore don't call your B
constructor explicitly, the compiler will assume that you want to call B
s default constructor. But your class B
does not have a default constructor, so you would get a compiler error like this:
prog.cpp: In constructor ‘D::D()’:
prog.cpp:31:20: error: no matching function for call to ‘B::B()’
D() : B1(), B2(){}
^
Therefore, you would have to do something like
class D : public B1, public B2
{
public:
D() : B(99), B1(), B2(){}
};
and this also solves your question: The value of x
will be whatever the most derived class wants it to be (99 in this case). Thus, there is no ambiguity.
PS: You also see, your question is at the heart of why it makes sense to have the special rule about virtual base class construction by the most derived class.