Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to explicitly code a default constructor when there are no other constructors?

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...?

like image 585
froadie Avatar asked Feb 18 '10 20:02

froadie


People also ask

Can default constructor be explicit?

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.

Do you always need a default constructor?

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.

Why do we need a default constructor?

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.

What happens if there is no default constructor?

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() .


2 Answers

A couple minor points that aren't likely to be why you saw it in this case.

  • It gives you something to set a breakpoint on.
  • You could make it non-public

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).

like image 115
Michael Burr Avatar answered Oct 12 '22 22:10

Michael Burr


It doesn't play any role and can safely be deleted.

like image 41
cherouvim Avatar answered Oct 12 '22 21:10

cherouvim