A special type of subroutine called at the creation of an object.

In object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created.

Most languages allow overloading the constructor in that there can be more than one constructor for a class, with differing parameters. Some languages take consideration of some special types of constructors.

Some types of constructors:

  • Default constructors
  • Copy constructors
  • Conversion constructors
  • Move constructors

Default constructors

If the programmer does not supply a constructor for an instantiable class, most languages will provide a default constructor. The behavior of the default constructor is language dependent. It may initialize data members to zero or other same values, or it may do nothing at all. In C++ a default constructor is required if an array of class objects is to be created. Other languages (Java, C#, VB .NET) have no such restriction.

Copy constructors

Copy constructors define the actions performed by the compiler when copying class objects. A copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object). It is used to create a copy of an existing object of the same class. Even though both classes are the same, it counts as a conversion constructor.

Conversion constructors

Conversion constructors provide a means for a compiler to implicitly create an object belonging to one class based on an object of a different type. These constructors are usually invoked implicitly to convert arguments or operands to an appropriate type, but they may also be called explicitly.

Move constructors

In C++, move constructors take an rvalue reference to an object of the class, and are used to implement ownership transfer of the parameter object's resources.