In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

A constructor resembles an instance method, but it differs from a method in that it has no explicit return type, it is not implicitly inherited and it usually has different rules for scope modifiers. Constructors often have the same name as the declaring class. They have the task of initializing the object's data members and of establishing the invariant of the class, failing if the invariant is invalid. A properly written constructor leaves the resulting object in a valid state. Immutable objects must be initialized in a constructor.

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. Constructors, which concretely use a single class to create objects and return a new instance of the class, are abstracted by factories, which also create objects but can do so in various ways, using multiple classes or different allocation schemes such as an object pool.

Types Parameterized constructors Constructors that can take at least one argument are termed as parameterized constructors. When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly. The method of calling the constructor implicitly is also called the shorthand method.

class Point { private: int x; int y; public: Point() = default; Point(int x, int y): x{x}, y{y} {} // Parameterized constructor

Point p = Point(0, 50); // Explicit call. Point p2(0, 50); // Implicit call.

Default constructors If the programmer does not supply a constructor for an instantiable class, Java compiler inserts a default constructor into the code. This constructor is known as default constructor. It would not be found in source code (the file) as it would be inserted into the code during compilation and exists in file. 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 Java, a "default constructor" refer to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class or in the absence of any programmer-defined constructors (e.g. in Java, 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 (integer types), 0.0 (floating-point types), false (boolean type), or null (reference types), etc.

class Point { private: int x; int y; public: Point(int x = 0, int y = 0); // Default constructor.

Copy constructors

Like C++, Java also supports "Copy Constructors". But, unlike C++, Java does not create a default copy constructor even if no such copy constructor is specified. 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. While copy constructors are usually abbreviated copy ctor or cctor, they have nothing to do with class constructors used in .NET using the same abbreviation.

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.

Syntax Java, C++, C#, ActionScript, , and MATLAB have a naming convention in which constructors have the same name as the class with which they are associated. In C and Rust (programming language), there are no language-level constructors. In C, objects are created by a struct initializer, or a function that creates such an instance of an object. Similarly in Rust, objects are created as struct literals, but may also include a constructor-like associated function (typically named new, from, etc.) In Crystal, similarly to Python, the constructor is split between two methods: new and initialize. The compiler defines the new method, requiring only that the user define initialize.new, initialize and allocate, from the Crystal Reference guide Although the Crystal compiler automatically defines it, the user may manually define new, and even forego use of default new and define their own constructors. In PHP 5, a recommended name for a constructor is __construct. For backwards compatibility, a method with the same name as the class will be called if __construct method can not be found. Since PHP 5.3.3, this works only for non-namespaced classes.Constructors and Destructors, from PHP online documentation In PHP 7, you should always name the constructor as __construct. Methods with the same name as the class will trigger an E_DEPRECATED level error. In Perl, constructors are, by convention, named "new" and have to do a fair amount of object creation. In Moose object system for Perl, constructors (named new) are automatically created and are extended by specifying a BUILD method. In Visual Basic .NET, the constructor is called "New". In Python, the constructor is split over two methods, "__new__" and "__init__". The __new__ method is responsible for allocating memory for the instance, and receives the class as an argument (conventionally called "cls"). The __init__ method (often called "the initialiser") is passed the newly created instance as an argument (conventionally called "self").Data model, from Python online documentation Object Pascal constructors are signified by the keyword "constructor" and can have user-defined names (but are mostly called "Create"). In Objective-C, the constructor method is split across two methods, "alloc" and "init" with the alloc method setting aside (allocating) memory for an instance of the class, and the init method handling the bulk of initializing the instance. A call to the method "new" invokes both the alloc and the init methods, for the class instance.

Memory organization In Java, C#, and VB .NET, the constructor creates reference type objects on the heap, whereas primitive types (such as int, double, etc.) are stored on the stack (though some languages allow for manually allocating objects on the stack through a stackalloc modifier). VB .NET and C# also allow the use of the new operator to create value type objects, but these value type objects are created on the stack regardless of whether the operator is used or not. In these languages, object destruction occurs when the object has no references and then gets destroyed by the garbage collector.

In C++, objects are created on the stack when the constructor is invoked without the new operator, and created on the heap when the constructor is invoked with the new operator (which returns a pointer to the object). Stack objects are deleted implicitly when they go out of scope, while heap objects must be deleted implicitly by a destructor or explicitly by using the delete operator. By using the "Resource Acquisition is Initialization" (RAII) idiom, resource management can be greatly simplified.

Language details Constructors are implemented in different programming languages in various ways, including:

C In C, there are no constructors. However, functions can be defined to create an object, similar to a constructor. #include <stdlib.h>

typedef struct { char* name; int age; } Person;

// this method creates an instance of Person Person* createPerson(const char name[], int age) { Person* p = (Person*)malloc(sizeof(Person)); if (!p) { return NULL;

strcpy(p->name, name); p->age = age; return p; }

// this method destroys an instance of Person void destroyPerson(Person* p) { if (p) { free(p->name); free(p);

C++ In C++, the name of the constructor is the name of the class. It returns nothing. It can have parameters like any member function. Constructor functions are usually declared in the public section, but can also be declared in the protected and private sections, if the user wants to restrict access to them.

The constructor has two parts. First is the initializer list which follows the parameter list and before the method body. It starts with a colon and entries are comma-separated. The initializer list is not required, but offers the opportunity to provide values for data members and avoid separate assignment statements. The initializer list is required if there are const or reference type data members, or members that do not have parameterless constructor logic. Assignments occur according to the order in which data members are declared (even if the order in the initializer list is different).https://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order Constructor The second part is the body, which is a normal method body enclosed in curly brackets. It is generally cheaper and better practice to use the initializer list as much as possible, and only use the constructor body for non-assignment operations and assignments where the initializer list cannot be used or is otherwise insufficient.

C++ allows more than one constructor. The other constructors must have different parameters. Additionally constructors which contain parameters which are given default values, must adhere to the restriction that not all parameters are given a default value. This is a situation which only matters if there is a default constructor. The constructor of a base class (or base classes) can also be called by a derived class. Constructor functions are not inherited and their addresses cannot be referenced. When memory allocation is required, the new and delete operators are called implicitly.

A copy constructor has a parameter of the same type passed as const reference, for example X(const X& rhs). If it is not provided explicitly, the compiler uses the copy constructor for each member variable or simply copies values in case of primitive types. The default implementation is not efficient if the class has dynamically allocated members (or handles to other resources), because it can lead to double calls to delete (or double release of resources) upon destruction.

import std;

class PolarPoint { private: double x; double y; public: explicit PolarPoint(double r = 1.0, double theta = 0.0): // Constructor, parameters with default values. x{r * std::cos(theta)}, y{r * std::sin(theta)} /* <- Initializer list */ { std::println("Point: x = {}, y = {}", x, y); // Constructor body

Example invocations: PolarPoint a; PolarPoint b(3); PolarPoint c(5, std::numbers::pi / 4);

On returning objects from functions or passing objects by value, the objects copy constructor will be called implicitly, unless return value optimization applies.