Default constructors (C++ only)

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(). This constructor is an inline public member of its class. The compiler will implicitly define A::A() when the compiler uses this constructor to create an object of type A. The constructor will have no constructor initializer and a null body.

The compiler first implicitly defines the implicitly declared C++11 beginsor explicitly defaultedC++11 ends constructors of the base classes and nonstatic data members of a class A before defining the implicitly declared C++11 beginsor explicitly defaultedC++11 ends constructor of A. No default constructor is created for a class that has any constant or reference type members.

A constructor of a class A is trivial if all the following are true:

  • It is implicitly declared C++11 beginsor explicitly defaultedC++11 ends.
  • A has no virtual functions and no virtual base classes
  • All the direct base classes of A have trivial constructors
  • The classes of all the nonstatic data members of A have trivial constructors

If any of the above are false, then the constructor is nontrivial.

A union member cannot be of a class type that has a nontrivial constructor.

Like all functions, a constructor can have default arguments. They are used to initialize member objects. If default values are supplied, the trailing arguments can be omitted in the expression list of the constructor. Note that if a constructor has any arguments that do not have default values, it is not a default constructor.

The following example defines a class with one constructor and two default constructors.
class X {
  X();                       // Default constructor with no arguments
  X(int = 0);                // Default constructor with one default argument
  X(int, int , int = 0);     // Constructor
Note: C++11 begins You can declare default constructors as explicitly defaulted functions or deleted functions. For more information, see Explicitly defaulted functions (C++11) and Deleted functions (C++11).C++11 ends