0

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) {}
};
2
  • 1
    The most derived class is responsible for constructing a virtual base. That's just how the language works. Commented Dec 4, 2014 at 22:22
  • 1
    Can you please check your code listings to be correct C++? There are a number of reasons this code won't compile and it's better if we don't have to guess which ones are related to your question and which ones are just typos. Commented Dec 4, 2014 at 22:24

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.