Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting-Constructors + In-Class-Initialization of non-default constructabe type fails

I am encountering the following error in my project:

error: use of deleted function ‘C::C(int)’ note: ‘C::C(int)’ is
implicitly deleted because the default definition would be ill-formed:
error: use of deleted function ‘M::M()’

This is the code I am using:

struct M {
    M(int){}
    M() = delete;  // Allowing this would work.
};

struct B {
    B(int) {}
    B() = delete;
};

struct C : public B {
    using B::B;
    M n = {5};

    // C(int i) : B(i) {}  // Adding this would work
};

C c{1};

Does anyone know why is this happening?


Clearly the language is willing to append more initialization on the end of the inherited constructor (as it's willing to call a default constructor). And clearly it's willing to implicitly add a call to the non-default constructor (the in class initialization) to the end of an explicitly defined constructor. But for some reason that I don't understand, it's not willing to do both at the same time.

According to this question, perfect forwarding isn't really perfect enough and shouldn't be used here.

Note: in the real case the constructor(s) for B are much more complex and subject to change, so manually forwarding stuff isn't really a viable option.

like image 655
BCS Avatar asked Aug 29 '14 18:08

BCS


People also ask

Can a class inherit constructor?

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.

How constructors are implemented when the classes are inherited?

When classes are inherited, the constructors are called in the same order as the classes are inherited. If we have a base class and one derived class that inherits this base class, then the base class constructor (whether default or parameterized) will be called first followed by the derived class constructor.

Can we inherit constructor in C++?

Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The constructors of inherited classes are called in the same order in which they are inherited.

What constructor is responsible for building an object of the derived class the one in the base class the one in the derived class or both?

When constructing a derived class, the derived class constructor is responsible for determining which base class constructor is called. If no base class constructor is specified, the default base class constructor will be used.


1 Answers

This is a GCC Bug and has now been reported.

like image 171
BCS Avatar answered Oct 05 '22 23:10

BCS