Declaring default constructor while invoking base class constructor

I am trying to implement the concept of invoking base class constructor and inheritance.I have written the following code but it is giving error when I don't declare the default constructor for class A, I wonder why am I getting the error.

#include <iostream>
using namespace std;

class A
{
    int a;
    public:
    A() {} //Default Constructor
    A(int x)
    {
        a=x;cout<<a;
        cout<<"A Constructor\n";
    }
};
class B: virtual public A
{
    int b;
    public:
    B(int x)
    {
        b=x;cout<<b;
        cout<<"B Constructor\n";
    }
};
class C: virtual public A
{
    int c;
    public:
    C(int x)
    {
        c=x;cout<<c;
        cout<<"C Constructor\n";
    }
};
class D: public B,public C
{
    int d;
    public:
    D(int p,int q,int r,int s):A(p),B(q),C(r)
    {
        d=s;cout<<d;
        cout<<"D Constructor\n";
    }
};
int main()
{
    D d(1,2,3,4);
    return 0;
}

Upvotes: 4

Views: 87

Answers (2)

R Sahu
R Sahu

Reputation: 206567

For the moment, let's simplify things and forget about existence of classes C an D.

If you construct an object of type B as

B b(10);

it will use B::B(int). In the implementation of B::B(int), the A part of B has to be initialized somehow. You have:

B(int x)
{
    b=x;cout<<b;
    cout<<"B Constructor\n";
}

which is equivalent to:

B(int x) : A()
{
    b=x;cout<<b;
    cout<<"B Constructor\n";
}

Since A does not have a default constructor, the compiler correctly reports that as an error.

You could fix that by using:

B(int x) : A(0)
{
    b=x;cout<<b;
    cout<<"B Constructor\n";
}

If would like to be able to pass another value to A(int) from B's constructor, you need to allow the user to construct a B using two arguments.

B(int x, int y = 0) : A(y)
{
    b=x;cout<<b;
    cout<<"B Constructor\n";
}

Upvotes: 1

Lucky
Lucky

Reputation: 367

If you dont call the constructor of the superclass in the subclass, the superclass must have a default constructor, because if you want to create an instance of B, there will be automatically created an instance of the superclass, which is not possible if there is no default constructor.

Upvotes: 2

Related Questions