Default constructor


In computer programming languages, the term default constructor can refer to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors, and is usually a nullary constructor. In other languages it is a constructor that can be called without having to provide any arguments, irrespective of whether the constructor is auto-generated or user-defined. Note that a constructor with formal parameters can still be called without arguments if default arguments were provided in the constructor's definition.

C++

In C++, the standard describes the default constructor for a class as a constructor that can be called with no arguments. For example:

class MyClass
MyClass::MyClass : x // constructor defined
int main

When allocating memory dynamically, the constructor may be called by adding parenthesis after the class name. In a sense, this is an explicit call to the constructor:

int main

If the constructor does have one or more parameters, but they all have default values, then it is still a default constructor. Remember that each class can have at most one default constructor, either one without parameters, or one whose all parameters have default values, such as in this case:

class MyClass
MyClass::MyClass // constructor defined

In C++, default constructors are significant because they are automatically invoked in certain circumstances; and therefore, in these circumstances, it is an error for a class to not have a default constructor:
If a class has no explicitly defined constructors, the compiler will implicitly declare and define a default constructor for it. This implicitly defined default constructor is equivalent to an explicitly defined one with an empty body. For example:

class MyClass
int main

If constructors are explicitly defined for a class, but they are all non-default, the compiler will not implicitly define a default constructor, leading to a situation where the class does not have a default constructor. This is the reason for a typical error, demonstrated by the following example.

class MyClass
MyClass::MyClass
int main

Since neither the programmer nor the compiler has defined a default constructor, the creation of the objected pointed to by p leads to an error.
On the other hand in C++11 a default constructor can be explicitly created:

class MyClass

Or explicitly inhibited:

class MyClass

Java and C#

In both Java and C#, a "default constructor" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class. The default constructor implicitly calls the superclass's nullary constructor, then executes an empty body. All fields are left at their initial value of 0, 0.0, false, or null. A programmer-defined constructor that takes no parameters is also called a default constructor in C#, but not in Java.