Consider we have a parent class A that has protected members x and y and a constructor:
A::A(int xpos, int ypos) : x(xpos), y(ypos) {}
Now consider we have two classes B and C that inherit from A and have constructors as defined below.
class B : public virtual A
B::B(int xpos, int ypos) : A(xpos,ypos) {}
class C : public virtual A
C::C(int xpos, int ypos) : A(xpos,ypos) {}
Finally let's have a class D that inherits both B and C.
class D : public B, public C
If I write Ds constructor as follows I get a compile error saying that Ds constructor must explicitly call As constructor.
D::D(int xpos, int ypos) : B(xpos,ypos), C(xpos,ypos) {}
Why is this? Surely this is problematic if I attempt to inherit from classes that I don't know anything about the classes constructor? Isn't it enough that B and C both explicitly call As constructor?
The rule for a virtual base is that the most-derived class calls its constructor. If that wasn't the case, which of the intermediate base classes should construct the one copy of the virtual base? Pretend for a moment that the constructor for your class B reverses the order of the arguments when it constructs A:
B::B(int xpos, int ypos) : A(ypos, xpos) {}
Now, what should the state of the A sub-object be? First constructor wins? Last one wins? Either way, it's fragile: changing the order of B and C in your D type would change how the A base class gets initialized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With