-1

Consider the following:

# include <iostream>

using namespace std;

class Base{
    public:
        Base(int a) {
            cout << "Base" << endl;
        }
};

class Child: public Base{
    public:
        Child(int a) {
            cout << "Child" << endl;
        }
};

int main() {
    Child c = Child(0);
}

On compilation the error no matching function for call to ‘Base::Base()’ is given. Explicitly declaring a default constructor for Base fixes this issue.

It seems to me that if I want to inherit from a class, then it needs to have a default constructor? Even though (in this example) it never gets called? Is this correct, and if so, why? Otherwise, what's wrong the above code?

cb7
  • 493
  • 4
  • 10
  • 1
    `Child(int a) {` -> `Child(int a) : Base (a) {`? There **must** be a duplicate somewhere, but I am too lazy to look for it :( – Algirdas Preidžius May 13 '19 at 14:00
  • 2
    Possibly duplicate? https://stackoverflow.com/q/120876/10077 – Fred Larson May 13 '19 at 14:02
  • If you add a constructor that takes no arguments `Base() { cout << "Foobar" << endl; }` it'll compile and you'll find that it is actually called. – Blaze May 13 '19 at 14:02
  • you implicitly call the default constructor `Base()`, so you need to define it. If you dont call it, you dont need it – 463035818_is_not_an_ai May 13 '19 at 14:03
  • If you don't explicitly call a particular constructor in your class initialization, then it calls the default constructor even if you don't see it in the code. Set a breakpoint to convince yourself of what I'm saying is true. So it's incorrect to say "it never gets called." You can give a default argument to your exisisting constructor and then it will act as a default constructor more or less. – Joseph Willcoxson May 13 '19 at 14:04

1 Answers1

3

No, that is not a correct assumption.

You just have an error. Your derived class constructor must call the one and only Base constructor you provide which is a one parameter constructor.

    Child(int a)
    : Base(a)
    {
        cout << "Child" << endl;
    }
acraig5075
  • 10,588
  • 3
  • 31
  • 50