Reputation: 37
I have a class structure that looks like the following:
O
|
A
/ \
B C
\ /
D
|
E
And the constructors work as follows (specific code not included for brevity, but I can flesh this out more if necessary):
class O {
protected:
O(const string &str) {
//Does stuff with str
};
}
class A : public O {
protected:
A(const string &str) : O(str) { };
}
class B : public virtual A {
protected:
B(const string &str) : A(str) { };
}
class C : public virtual A {
protected:
C(const string &str) : A(str) { };
}
class D : public B, public C {
protected:
D(const string &str) : B(str), C(str) { };
}
class E : public D {
public:
E(const string &str) : D(str) { };
}
Classes O, A, B, C, and D are supposed to be part of a library with class D being the base class for any classes I make later (such as E). The only purpose of D is to simplify inheritance for classes like E. My problem is that the constructor of E calls the default constructor of A unless I explicitly call A's parameterized constructor, which defeats the purpose of D.
This inheritance structure is best for my application because classes C & D are being used to specialize an infrastructure created by A & B. C contains additional methods for A.
Is there a way I can make D handle the call to A's parameterized constructor? Ideally, I would like an initialization of E to call the constructors A, B, C, D, E in that order. The string parameter is very important to classes upstream of O, and the constructors B and C need to run specific functions.
Upvotes: 3
Views: 584
Reputation: 146930
No. Virtual base classes must always be constructed by the most derived class. It cannot work any other way. All you can do is not permit A to be default constructible and have the compiler help you out, or refactor your code to not use diamond inheritance in the first place.
Upvotes: 5