When am I supposed to use the default
keyword in C++11?
Is it now considered bad to write
struct Foo {
};
and one should write
struct Foo {
Foo() = default;
};
?
When am I supposed to use the default
keyword in C++11?
Is it now considered bad to write
struct Foo {
};
and one should write
struct Foo {
Foo() = default;
};
?
Think of a case when the default constructor will not be provided by the compiler. Then you can use = default
to tell the compiler to create a default constructor for you anyway.
Otherwise (and unless you need a special default constructor) there's no reason to specify a default constructor in any way (with or without = default
).
In your example, there's no need for the "explicit" = default
constructor. It's more a question of style.
As mentioned here, a default constructor is not generated when you create a constructor with arguments. In those cases, using the default
keyword generates the default constructor for the class.
However, consider very carefully whether the object you're dealing with really should have a default constructor; that is, if the default initialisation of other objects is the right thing to do. Keep in mind that POD members are not initalised by default and may contain garbage data without data member initalisers.
This seems to be an opinion based question. However, it seems that the first option is most commonly used, as the second option is more verbose, and programmers tend not to use default unless a default operation must be delete
ed.
If you provide an explicit non-default constructor, you won't get the compiler provided default. In that case, you may used the default keyword to force the compiler to provide it.
The other case is if you'd like to make sure your default constructor has a specific protection level. For example, you may want to make sure your default constructor is private or protected.