Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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 it’s 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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading