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:
D(int _a, int _b, int _c): A(_a), B(_b, _a), C(_c, _a) {}
Because A
is a virtual base class, the D
constructor must initialize it despite the fact that it is not a direct base class. When an object of most derived type D
is being constructed, D::D
will first initialize A
, and then run the constructors for B
and C
. When the B
and C
constructors run, they will ignore the virtual base class A
, since D
already initialized it.