Is there any difference between a default user-defined constructor
class Simple
{
public:
Simple() {}
};
and a user-defined constructor that takes multiple arguments but has defaults for each of these
class WithDefaults
{
public:
WithDefaults(int i = 1) {}
};
other than that WithDefaults
can also be constructed with an explicit value for i
?
Specifically, I am wondering, as far as the language is concerned, if these two constructors play the exact same roll of default constructor for both, or if there are subtle differences between the properties of the classes?
In other words, is a constructor which has default values for all of its arguments a default constructor in every way?
A default constructor is a 0 argument constructor which contains a no-argument call to the super class constructor. To assign default values to the newly created objects is the main responsibility of default constructor.
Constructor has same name as the class itself. Default Constructors don't have input argument however, Copy and Parameterized Constructors have input arguments. Constructors don't have return type. A constructor is automatically called when an object is created.
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() .
It is possible to have a constructor with default arguments.. It means that if the constructor is defined with n parameters, we can invoke it with less than n arguments specified in the call.
Current Standard working draft N4527 [12.1p4]:
A default constructor for a class
X
is a constructor of classX
that either has no parameters or else each parameter that is not a function parameter pack has a default argument. [...]
So yes, the constructor of the second class is a perfectly valid default constructor.
Just a note that the wording in the published versions of C++11 and 14 was slightly different, but doesn't make a difference for your question. It used to be:
A default constructor for a class
X
is a constructor of classX
that can be called without an argument.
The change to the current wording was made as a result of DR 1630, in order to clarify the semantics of default initialization. Previously, there were places in the standard that referred to "the default constructor", implying that there can be only one; the current wording is intended to support more complex scenarios, where you can potentially have several such constructors (for example using SFINAE), and the one used is chosen using normal overload resolution.
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