Inheriting constructors

C++InheritanceGccConstructor

C++ Problem Overview


Why does this code:

class A
{
    public: 
        explicit A(int x) {}
};

class B: public A
{
};

int main(void)
{
    B *b = new B(5);
    delete b;
}

Result in these errors:

main.cpp: In function ‘int main()’:
main.cpp:13: error: no matching function for call to ‘B::B(int)’
main.cpp:8: note: candidates are: B::B()
main.cpp:8: note:                 B::B(const B&)

Shouldn't B inherit A's constructor?

(this is using gcc)

C++ Solutions


Solution 1 - C++

If your compiler supports C++11 standard, there is a constructor inheritance using using (pun intended). For more see Wikipedia C++11 article. You write:

class A
{
    public: 
        explicit A(int x) {}
};

class B: public A
{
     using A::A;
};

This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.

Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.


For templated base classes, refer to this example:

using std::vector;
    
template<class T>
class my_vector : public vector<T> {
    public:
    using vector<T>::vector; ///Takes all vector's constructors
    /* */
};

Solution 2 - C++

Constructors are not inherited. They are called implicitly or explicitly by the child constructor.

The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.

class A
{
public: 
    explicit A(int x) {}
};

class B: public A
{
public:
    explicit B(int x) : A(x) { }
};

UPDATE: In C++11, constructors can be inherited. See Suma's answer for details.

Solution 3 - C++

This is straight from Bjarne Stroustrup's page:

If you so choose, you can still shoot yourself in the foot by inheriting constructors in a derived class in which you define new member variables needing initialization:

struct B1 {
	B1(int) { }
};

struct D1 : B1 {
	using B1::B1; // implicitly declares D1(int)
	int x;
};

void test()
{
	D1 d(6);	// Oops: d.x is not initialized
	D1 e;		// error: D1 has no default constructor
}

note that using another great C++11 feature (member initialization):

 int x = 77;

instead of

int x;

would solve the issue

Solution 4 - C++

You have to explicitly define the constructor in B and explicitly call the constructor for the parent.

B(int x) : A(x) { }

or

B() : A(5) { }

Solution 5 - C++

How about using a template function to bind all constructors?

template <class... T> Derived(T... t) : Base(t...) {}

Solution 6 - C++

Correct Code is

class A
{
    public: 
      explicit A(int x) {}
};

class B: public A
{
      public:
             
     B(int a):A(a){
          }
};

main()
{
    B *b = new B(5);
     delete b;
}

Error is b/c Class B has not parameter constructor and second it should have base class initializer to call the constructor of Base Class parameter constructor

Solution 7 - C++

Here is how I make the derived classes "inherit" all the parent's constructors. I find this is the most straightforward way, since it simply passes all the arguments to the constructor of the parent class.

class Derived : public Parent {
public:
  template <typename... Args>
  Derived(Args&&... args) : Parent(std::forward<Args>(args)...) 
  {

  }
};

Or if you would like to have a nice macro:

#define PARENT_CONSTRUCTOR(DERIVED, PARENT)                    \
template<typename... Args>                                     \
DERIVED(Args&&... args) : PARENT(std::forward<Args>(args)...)

class Derived : public Parent
{
public:
  PARENT_CONSTRUCTOR(Derived, Parent)
  {
  }
};

Solution 8 - C++

derived class inherits all the members(fields and methods) of the base class, but derived class cannot inherit the constructor of the base class because the constructors are not the members of the class. Instead of inheriting the constructors by the derived class, it only allowed to invoke the constructor of the base class

class A
{
    public: 
        explicit A(int x) {}
};

class B: public A
{
       B(int x):A(x);
};

int main(void)
{
    B *b = new B(5);
    delete b;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSydiusView Question on Stackoverflow
Solution 1 - C++SumaView Answer on Stackoverflow
Solution 2 - C++AviView Answer on Stackoverflow
Solution 3 - C++nenchevView Answer on Stackoverflow
Solution 4 - C++grepsedawkView Answer on Stackoverflow
Solution 5 - C++PraduView Answer on Stackoverflow
Solution 6 - C++Iqbal HaiderView Answer on Stackoverflow
Solution 7 - C++Eugen BondarevView Answer on Stackoverflow
Solution 8 - C++Sarath GovindView Answer on Stackoverflow