Search code examples
c++inheritancec++17default-constructor

Why in order to use default constructor in Derived Class, we need a default constructor in the Base Class


As you have seen in the title i need to find the error in the code bellow, Here is what i know:

  • I know that in order to use default constructor in B, we need a default constructor in A

What i don't know is:

  • Why? I guess it's because B inherits A but i need to know exactly why exactly

Here is the code:

#include <iostream>

using namespace std;

class A 
{    
    protected:
        int i;
    public:
        A(int i) :i (i) {}
};

struct B : A
{
    B() {}
    void set(int i) { this-> i = i; }
    void print() { cout << i << endl; }
};

int main()
{
    B b; b.set(2);
    b.print();
}

Solution

  • I think your title is misleading, but the question is valid.

    In order to construct B, A needs to be constructed as well (that you know) but how can A be constructed without knowing the value of int i in its constructor?

    But you could use the parameter-less constructor of B to provide value for i:

    struct B : public A {
      public:
        B(): A(53 /* value for int i */) { }
    ...
    

    but unless you specify what constructor of A should B use, the compiler will search for the default constructor (which does not exist in A`s case)