C++ Inheritance – How to Inherit Base Class Constructor

c++

For the following code:

struct Base
{
protected:
    Base(){}
    Base(int) {}
};


struct Derive : public Base
{
public:
    using Base::Base;
};


int main()
{
    Derive d1;
    Derive d2(3);
}

Seems d1 can be constructed correctly, but d2 cannot be constructed.

SO my question is: Why using Base::Base can only change the default constructor to public and keep the constructor with a int parameter as protected?

Thanks a lot!

Best Answer

If you want to send parameters to base class constructor, you need to send the parameters through derived class constructor only.

using in your code is no use like below. Below function works fine.

#include <iostream>

using namespace std;

struct Base
{
protected:
    Base() {}
    Base(int) {}
};


struct Derive : public Base
{
public:
    //using Base::Base;
};


int main()
{
    Derive d1;
    //Derive d2(3);
    return 0;
}

Note that I didn't use 'using'. But as I am not passing any parameters to 'd1' object, through derived class default constructor, base class constructor (constructor with no arguments) will be called. But if you want to send parameters to base class, you need to send it through derived class only like below.

#include <iostream>

using namespace std;

struct Base
{
protected:
    Base() {}
    Base(int y) {};
};


struct Derive : public Base
{
public:
    Derive()
    {
        
    };
    
    Derive(int x) : Base(x) {
    }
};


int main()
{
    Derive d1;
    Derive d2(3);
    return 0;
}
Related Question