Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit and overload default constructor

I've been searching for this and I'm amazed I haven't found anything. Why can't I inherit a base class constructor using using declaration and add an overload in the derived class? I'm using Visual C++ 2013, the base class constructor is ignored when default-constructing b:

error C2512: 'B' : no appropriate default constructor available

I've dealt with this by re-defining the constructors, but I don't like that. This is just a minimal example, it wouldn't bother me if I had only one base class constructor.

struct A
{
    A() : a(10) {}

    int a;
};

struct B : A
{
    using A::A;

    explicit B(int a) { this->a = a; }
};

int main()
{
    B b;
}
like image 347
LogicStuff Avatar asked Apr 06 '15 18:04

LogicStuff


People also ask

Can we overload the default constructor?

A default constructor cannot be overloaded in the same class. This is because once a constructor is defined in a class, the compiler will not create the default constructor. Thus, an attempt to overload the default constructor will effectively remove it from the class. The constructor must not use a different name.

Is default constructor inherited in Java?

A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this.

Can we overload default constructor in C++?

In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments. This concept is known as Constructor Overloading and is quite similar to function overloading.

How do you overload a default constructor in Java?

Using this() in constructor overloading this() reference can be used during constructor overloading to call default constructor implicitly from parameterized constructor. Please note, this() should be the first statement inside a constructor.


1 Answers

The problem is that default-constructors are not inherited. From [class.inhctor]/p3:

For each non-template constructor in the candidate set of inherited constructors [..], a constructor is implicitly declared with the same constructor characteristics unless there is a user-declared constructor with the same signature in the complete class where the using-declaration appears or the constructor would be a default, copy, or move constructor for that class.

You also have a user-declared constructor that suppresses the creation of an implicit default-constructor. Just add a defaulted one to make it work:

B() = default;
like image 177
David G Avatar answered Oct 21 '22 12:10

David G