Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance: No appropriate default constructor available

I get the error: No appropriate default constructor for B. However, I don't understand why the compiler wants to call a default constructor, when I give the arguments ii and DONT want to call the default.

#include <iostream>
using namespace std;

class A {
    int i;
public:
    A(int ii) { i = ii; cout << "Constructor for A\n"; }
    ~A() { cout << "Destructor for A\n"; }
    void f() const{}
};

class B {
    int i;
public:
    B(int ii) { i = ii; cout << "Constructor for B\n"; }
    ~B() { cout << "Destructor for B\n"; }
    void f() const{}
};

class C:public B {
    A a;
public:
    C() { cout << "Constructor for C\n"; }
    ~C() { cout << "Destructor for C\n"; }
    void f() const {
        a.f();
        B::f();
    }
};

class D:public B {
    C c;
public:
    D(int ii) { B(ii); cout << "Constructor for D\n"; }
    ~D() { cout << "Destructor for D\n"; }
};

int main() {
    D d(47);
}
like image 240
code12098 Avatar asked Sep 10 '26 15:09

code12098


1 Answers

Your parent constructor should be called in the initializer list:

class D:public B {
    C c;
public:
    D(int ii) : B(ii)/* <- */ { cout << "Constructor for D\n"; }
    ~D() { cout << "Destructor for D\n"; }
};

Note the /* <- */ comment. That needs to be changed.

What you are doing right now is to create an instance of B() in you class D constructor, which is not being used:

D(int ii) { B(ii); /* <- useless*/ }
like image 158
mfontanini Avatar answered Sep 13 '26 05:09

mfontanini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!