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;
?
Using = delete is for prohibiting the use of one of the functions, and that = default is used if you want to be explicit to the compiler on where to use the defaults for these functions.
It means the compiler should immediately stop compiling and complain "this function is deleted" once the user use such function. If you see this error, you should check the function declaration for =delete .
Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .
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.Is there any reason (use case) to allow = default for D's constructor, when it's actually works as = delete;?
It doesn't work as =delete
. It says just what it's supposed to say. That you explicitly want the compiler generated default implementation.
It just so happens that the compiler generated one has to be defined deleted. Because the default constructor of B
is implicitly deleted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With