Search code examples
c++c++11default-constructor

Using =default in meaning of =delete


The following code is well compiled:

struct B { 
    B(int) {} 
};

struct D : B {
    D() = default;
};

Until I have to create an instance of class D:

D d; // error: use of deleted function 'D::D()'

Is there any reason (use case) to allow = default for D's constructor, when it's actually works as = delete;?


Solution

  • g++ gives a nice explanation in the error:

    bla.cpp:6:5: note: ‘D::D()’ is implicitly deleted because the default definition would be ill-formed: D() = default;

    The default constructor will attempt to construct all parts of D. You have no fields, but it has an initial B - which has no empty constructor, only an int one.

    The default behavior makes sense - D shouldn't have an empty constructor unless it explicitly states which int to construct the B with, and the compiler doesn't want to guess. Otherwise you will have a D object, and depending on what happens in the B constructor B may contain junk, for example if initializing a field.

    I'm not sure if you meant your question literally when you ask why is this "allowed", as the B default constructor is deleted, but I can think of two reasons:

    1. This behavior is well defined, and there is no reason to disallow it. Detecting the error only when you attempt to construct something illegally is done anyway.
    2. It's more flexible - changing B to have a default constructor will automatically allow D to have one.