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 1:
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)
Solution 2:
The magic sauce is that before entering the body of the constructor all member variables and base classes must have been fully constructed.
That means A
must be constructed, A(int i)
must be called, and that this-> i = i;
is an assignment, not an initialization, and cannot replace the initialization of i
performed by A
's constructor.