0

This is a code fro diamond tree problem of multiple inheritance and according to me this code is cool but it is showing some error on compilation ..help me to figure the error

#include<iostream>
using namespace std;

class A  //A Diamond tree problem
{
  int x;
public:
  A(int i) { x = i; }
  void print() { cout << x; }
};

class B: virtual public A
{
public:
  B():A(10) {  }
};

class C:  virtual public A 
{
public:
  C():A(20) {  }
};

class D: public B, public C{
};

int main()
{
    D d;
    d.print();
    return 0;
}
2
  • 8
    What is the error you get? Commented May 27, 2013 at 12:28
  • It gives an error because A needs to have a default constructor. Or you need to add a constructor to D which calls the A constructor. Commented May 27, 2013 at 12:31

2 Answers 2

8

It would be useful to see the error:

In constructor ‘D::D()’:
error: no matching function for call to ‘A::A()’

When using virtual inheritance, the virtual base class must be initialised by the most derived class. In this case, that is D; so in order to be able to instantiate D, it must initialise A:

class D: public B, public C
{
public:
    D():A(42) {}
};

Alternatively, you could provide A with a default constructor. Declaring any constructor will prevent the compiler from implicitly generating one for you.

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

2 Comments

Can you explain a little more? Wouldn't compiler provide a default constructor? is it a specific behavior of virtual inheritance
@bapusethi: You only get an implicit default constructor if you don't declare any constructors of your own. Declaring A(int) will prevent that. That's true for all classes, regardless of virtual inheritance.
3

You need to provide default construct for D and call A in member initialize list:

class D: public B, public C{
public:
   D():A(30){}
};

Or you could provide a default A constructor

A():x(0) {}

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.