Declaring a default constructor when calling a base class constructor

I am trying to implement the concept of calling the base class constructor and inheritance. I wrote the following code, but it gives an error when I do not declare a default constructor for class A, I am wondering why I am getting an 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;
}
+4
source share
2 answers

If you do not call the superclass constructor in the subclass, the superclass must have a default constructor, because if you want to instantiate B, the superclass will be instantiated automatically, which is impossible if there is no default constructor.

+2
source

For now, simplify things and forget about the existence of classes Ca D.

B

B b(10);

B::B(int). B::B(int) A B - . :

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

:

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

A , .

, :

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

A(int) B, B .

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

Source: https://habr.com/ru/post/1688028/


All Articles