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;
?
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:
B
to have a default constructor will automatically allow D
to have one.