Reputation: 823
Have a problem with multiple inheritance. I have solved diamond problem:
class A
{
int m;
int n;
public:
A(int x, int y)
{
m = x; n = y
}
fA() {}
};
class B : virtual public A // B has fA(),fB()
{
public:
B(int k) : A(1, k) {}
fB() {}
};
class C : virtual public A // C has fA(),fC()
{
public:
C(int k) : C(2, k) {}
fC() {}
};
class D : public B, public C // D has fA(),fB(),fC()
{
public:
D(int k) : B(k),C(k),A(3,k)
};
This is working well. Problem with this:
class S : public B // S has fA(),fB()
{
public:
S() : B(6) {}
};
Compilator shows me: "error: no matching function for call to `A::A()'"
This code is working, but it doesn't satisfied me:
class S : public B // S has fA(),fB()
{
public:
S() : B(6),A(1,6) {}
};
Upvotes: 0
Views: 119
Reputation: 55395
In virtual inheritance, the constructor of virtual base is called from the constructor of most derived class:
class S : public B // S has fA(),fB()
{
public:
S() : B(6) {}
}; // ^ A base class is initialized at this point, before B
This also means that other explicit calls to A
's constructor in initialization-lists further down the inheritance chain are ignored:
class B : virtual public A // B has fA(),fB()
{
public:
B(int k) : A(1, k) {}
fB() {} // ^^^^^^^ this call is ignored when B is a part of S object
};
If there's no explicit call to virtual base's constructor in initialization list of most derived class, the compiler will (of course) try to call the default constructor. But A
doesn't have one and that's your problem.
One solution you already discovered yourself. The other is to write default constructor for A
.
Upvotes: 6