Chaining constructors across inheritance in C# is handy and useful. What’s the best way to implement similar functionality in C++? This is what I’d like to express:
struct A
{
A(int p)
{
i = p;
}
int i;
};
struct B : virtual A
{
B(int q) : A(q)
{
}
};
struct C : virtual B
{
C(int r) : B(r) // call B::B() which in turn would call A::A()
{
}
};
Any ideas?
Cheers,
Charlie.
In C++, virtual inheritance requires the constructor of the most derived type to explicitly call the constructor of all the virtual bases:
While you have clearly stated that you need virtual inheritance, it is uncommon to use virtual inheritance, so you might want to explain the use case. There might be alternatives that don’t require this and will thus allow the chaining of the constructors.
In case you wondered by the most derived type needs to call the constructor, the reason is that
virtualinheritance means there will be only one such base in the complete object. Now if you consider a possible relation:What value should be passed to constructor of the single instance of
baseinsidefinal? The two different inheritance paths are passing conflicting values, but there is a single object to initialize. Even if the different calls were not conflicting, with a separate compilation model, the compiler cannot know that, so the only option is that the complete object decides how to initialize the virtual bases.