I recently saw this constructor in a class:
public MyClass(){ }
There were no other constructors.
Is there a reason for this? Java automatically creates a default constructor, so why would you declare one explicitly? Or is this considered good practice in the same way as using braces for single-statement if statements - in case other constructors are added later and you forget that you don't have a default...?
A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value initialization (8.5). It goes on to provide an example of an explicit default constructor, but it simply mimics the example I provided above.
What is the default constructor? Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors.
The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.
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() .
A couple minor points that aren't likely to be why you saw it in this case.
As far as "in case other constructors are added later and you forget that you don't have a default" - that might be a reason, I suppose. But if a non-default constructor were added, any code that used the default constructor would fail to compile, so the guy adding the new constrcutor would generally need to also add a defintion for the default ctor as well.
Then again, I can't think of any particular harm in having the empty ctor defined (though now that I've typed that, I get a feeling that someone might point out some corner of C++ where it could bite you).
It doesn't play any role and can safely be 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