Let us consider ordinary diamond problem but slightly improved. Now class A
have constant fields.
struct A {
const int a;
A (int _a): a(_a) {}
};
struct B: virtual A {
const int b;
B(int _b, int _a): A(_a), b(_b) {}
};
struct C: virtual A {
const int c;
C(int _c, int _a): A(_a), c(_c) {}
};
struct D: B, C {
D(int _a, int _b, int _c): ??? {}
};
So, what would be sensible to write instead of question marks? Or maybe it can be solved different way?
The constructor may be written as follows:
Because
A
is a virtual base class, theD
constructor must initialize it despite the fact that it is not a direct base class. When an object of most derived typeD
is being constructed,D::D
will first initializeA
, and then run the constructors forB
andC
. When theB
andC
constructors run, they will ignore the virtual base classA
, sinceD
already initialized it.