As I posted here, virtual inheritence in C++ is a pain. Today I realized that it is also viral.
Suppose the same inheritence as the last time and add a new class D inheriting from B1. As in the former case there was a diamond the inheritence between A and B1 is virtual. From D's point of view you have the following code:
class A {
public:
A(int i) { /* ... */ }
};
class B1 : public virtual A {
public:
B1() : A(0) { }
};
class D : public B1 {
public:
D() : B1() { }
};
This is a normal inheritence scenario. D's constructor calls its parent constructor and this one calls the grand parent's constructor and everything is fine, right? No. this example does not compile. GCC says: "In constructor 'D::D()': error: no matching function for call to 'A::A()'".
Yeah, right, D must call its grand parent's constructor, because B1's inheritence from A is virtual. This means: once you decide to use a class as the top of a diamond this has consequences for all uses of this class. Args!
No comments:
Post a Comment