Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
No edit summary
Tags: Visual edit Mobile edit Mobile web edit
 
(64 intermediate revisions by 41 users not shown)
Line 1:
{{Short description|Special function called to create an object}}
 
{{ProgLangCompare}}
In [[class-based programming|class-based]] [[object-oriented programming]], a '''constructor''' (abbreviation: '''ctor''') is a special type of [[subroutine]] called to [[object creation|create an object]]. It prepares the new object for use, often accepting [[Parameter_(computer_programming)|arguments]] that the constructor uses to set required [[member variable]]s.
 
In [[class-based programming|class-based]], [[object-oriented programming]], a '''constructor''' (abbreviation: '''ctor''') is a special type of [[Function (computer programming)|function]] called to [[object creation|create an object]]. It prepares the new object for use, often accepting [[Parameter (computer programming)|arguments]] that the constructor uses to set required [[member variable]]s.

A constructor resembles an [[methodMethod (computer scienceprogramming)|instance method]], but it differs from a method in that it has no explicit [[return type]], it is not implicitly [[inheritance (object-oriented programming)|inherited]] and it usually has different rules for scope modifiers. Constructors often have the same name as the declaring [[class (computer science)|class]]. They have the task of [[initialization (computing)|initializing]] the object's [[data member]]s and of establishing the [[Class invariant|invariant of the class]], failing if the invariant is invalid. A properly written constructor leaves the resulting [[object (computer science)|object]] in a ''valid'' state. [[Immutable object]]s must be initialized in a constructor.
 
Most languages allow [[method overloading|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 [[Factory (object-oriented programming)|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.
 
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. If we want to initialize fields of the class with your own values, then use a parameterized constructor.
 
<syntaxhighlight lang="cpp">
class ExamplePoint {
private:
public:
Example() int x;
int y;
Example(int a, int b); // Parameterized constructor.
public:
 
Point() = default;
prate:
Point(int x, int x_;y):
x{x}, y{y} {} // Parameterized constructor
int y_;
};
 
Example::Example() = default;
 
Example::Example(int x, int y) : x_(x), y_(
</syntaxhighlight>
 
<syntaxhighlight lang="cpp">
ExamplePoint ep = ExamplePoint(0, 50); // Explicit call.
ExamplePoint e2p2(0, 50); // Implicit call.
</syntaxhighlight>
 
=== Default constructors ===
If the programmer does not supply a constructor for an instantiable class, Java compiler inserts a [[default constructor]] into your code on your behalf. This constructor is known as default constructor. You would not find it in your source code (the java file) as it would be inserted into the code during compilation and exists in .class 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 (computer science)|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)...
 
<syntaxhighlight lang="cpp">
class Point {
#include <iostream>
private:
 
int x;
class Student {
int y;
public:
public:
Student(int a = 0, int b = 0); // Default constructor.
Point(int x = 0, int y = 0); // Default constructor.
 
int a;
int b;
};
</syntaxhighlight>
Line 51 ⟶ 44:
=== Copy constructors ===
{{see also|Copy constructor (C++)}}
Like C++, Java also supports "Copy ConstructorConstructors". But, unlike C++, Java doesn’tdoesn't create a default copy constructor if you don’tdon't write your own. 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 constructor (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.
 
In C++, [[C++11#Rvalue references and move constructors|move constructors]] take a value reference to an object of the class, and are used to implement ownership transfer of the parameter object's resources.
 
== Syntax ==
* [[Java (programming language)|Java]], [[C++]], [[C Sharp (programming language)|C#]], [[ActionScript]], {{nowrap|[[PHP]] 4}}, and [[MATLAB]] have a naming convention in which constructors have the same name as the class with which they are associated.
 
* [[Java (programming language)|Java]],In [[C++]], [[C SharpRust (programming language)|C#Rust]], [[ActionScript]], {{nowrap|[[PHP]] 4}} and [[MATLAB]] have a namingthe convention infor whichthe constructors"constructor" haveis the sameto name as the class with which they areit associated<code>new</code>.
* In PHP 5, a recommended name for a constructor is <code>__construct</code>. For backwards compatibility, a method with the same name as the class will be called if <code>__construct</code> method can not be found. Since PHP 5.3.3, this works only for non-namespaced classes.<ref name="php5cpnstructor">[http://www.php.net/manual/en/language.oop5.decon.php Constructors and Destructors], from PHP online documentation</ref>
* In PHP 7, you should always name the constructor as <code>__construct</code>. Methods with the same name as the class will trigger an E_DEPRECATED level error.<ref name="php5cpnstructor">[http://www.php.net/manual/en/language.oop5.decon.php Constructors and Destructors], from PHP online documentation</ref>
* In [[Perl]], constructors are, by convention, named "new" and have to do a fair amount of object creation.
* In [[Moose perl|Moose object system]] for Perl, constructors (named ''new'') are automatically created and are extended by specifying a ''BUILD'' method.
Line 75 ⟶ 66:
 
== Memory organization ==
In Java, C#, and VB .NET, the constructor creates reference type objects on the heap, whereas primitive types (such as <code>int</code>, <code>double</code>, etc.) are stored on the [[Stack-based memory allocation|stack]] (though some languages allow for manually allocating objects on the stack through a <code>stackalloc</code> modifier). VB .NET and C# also allow the use of the <code>new</code> 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 <code>new</code> operator, and created on the heap when the constructor is invoked with the <code>new</code> 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 <code>delete</code> operator. By using the "[[Resource Acquisition is Initialization]]" (RAII) idiom, resource management can be greatly simplified.
In Java, C#, and VB .NET, the constructor creates reference type objects in a special memory structure called the
"[[heap (data structure)|heap]]". Value types (such as int, double, etc.) are created in a sequential structure called the "[[stack (abstract data type)|stack]]".
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.
 
== Language details ==<!-- see also Category:Programming language comparisons -->
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. 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.
Constructors are implemented in different [[programming language]]s in various ways, including:
 
=== Language detailsC++ ===
In [[C++]], the name of the constructor is the name of the class. It returns nothing. It can have parameters like any [[Method (computer programming)|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 (computer science)|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 you have ''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).<ref>https://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order Constructor</ref> 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.
{{Split|Comparison of programming languages (OOP, constructors)|date=May 2016}} <!-- see also Category:Programming language comparisons -->
 
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.
=== Java ===
 
A copy constructor has a parameter of the same type passed as ''const'' reference, for example ''Vector(const Vector& 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.
In [[Java (programming language)|Java]], constructors differ from other methods in that:
 
<syntaxhighlight lang="cpp">
* Constructors never have an explicit return type.
import std;
* Constructors cannot be directly invoked (the keyword “<code>new</code>” invokes them).
* Constructors cannot be ''synchronized'', ''final'', ''abstract'', ''native'', or ''static''.
* It should not contain modifiers
 
class PolarPoint {
Java constructors perform the following tasks in the following order:
private:
 
double x;
# Call the default constructor of the superclass if no constructor is defined.
double y;
# Initialize member variables to the specified values.
public:
# Executes the body of the constructor.
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 */ {
Java permit users to call one constructor in another constructor using <code>this()</code> keyword.
std::println("Point: x = {}, y = {}", x, y); // Constructor body
But <code>this()</code> must be first statement. <ref>[https://ranjeetkumarmaurya.wordpress.com/2017/02/06/constructor-in-java/ Details on Constructor in java]</ref>
 
<syntaxhighlight lang="java">
class Example
{
Example() // Non-parameterized constructor
{
this(1); // Calling of constructor
System.out.println("0-arg-cons");
}
};
Example(int a) // Parameterized constructor
{
System.out.println("1-arg-cons");
}
}
public static void main(String[] args)
{
Example e = new Example();
}
</syntaxhighlight>
Example invocations:
 
<syntaxhighlight lang="cpp">
Java provides access to the [[superclass (computer science)|superclass's]] constructor through the <code>super</code> keyword.
PolarPoint a;
 
PolarPoint b(3);
<syntaxhighlight lang="java">
PolarPoint c(5, std::numbers::pi / 4);
public class Example
{
// Definition of the constructor.
public Example()
{
this(1);
}
 
// Overloading a constructor
public Example(int input)
{
data = input; // This is an assignment
}
 
// Declaration of instance variable(s).
private int data;
}
</syntaxhighlight>
 
On returning objects from functions or passing objects by value, the objects copy constructor will be called implicitly, unless [[return value optimization]] applies.
<syntaxhighlight lang="java">
// Code somewhere else
// Instantiating an object with the above constructor
Example e = new Example(42);
</syntaxhighlight>
 
C++ implicitly generates a default copy constructor which will call the copy constructors for all base classes and all member variables unless the programmer provides one, explicitly deletes the copy constructor (to prevent cloning) or one of the base classes or member variables copy constructor is deleted or not accessible (private). Most cases calling for a customized '''copy constructor''' (e.g. [[reference counting]], [[deep copy]] of pointers) also require customizing the '''destructor''' and the '''copy assignment operator'''. This is commonly referred to as the [[Rule of three (C++ programming)|Rule of three]].
A constructor taking zero number of arguments is called a "no-arguments" or "no-arg" constructor.<ref>{{cite web|url=http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html|title= Providing Constructors for Your Classes |author=|publisher=Oracle Corporation|date=2013|accessdate=2013-12-20}}</ref>
 
=== JavaScript ===
 
As of ES6, [[JavaScript]] has direct constructors like many other programming languages. They are written as such
 
<syntaxhighlight lang="javascript">
class FooBar {
constructor(baz) {
this.baz = baz
}
}
</syntaxhighlight>
 
This can be instantiated as such
 
<syntaxhighlight lang="javascript">
const foo = new FooBar('7')
</syntaxhighlight>
 
The equivalent of this before ES6, was creating a function that instantiates an object as such
 
<syntaxhighlight lang="javascript">
function FooBar (baz) {
this.baz = baz;
}
</syntaxhighlight>
 
This is instantiated the same way as above.
 
=== Visual Basic .NET ===
 
In [[Visual Basic .NET]], constructors use a method declaration with the name "<code>New</code>".
 
<syntaxhighlight lang="vbnet">
Class Foobar
Private strData As String
 
' Constructor
Public Sub New(ByVal someParam As String)
strData = someParam
End Sub
End Class
</syntaxhighlight>
 
<syntaxhighlight lang="vbnet">
' code somewhere else
' instantiating an object with the above constructor
Dim foo As New Foobar(".NET")
</syntaxhighlight>
 
=== C# ===
 
Example [[C Sharp (programming language)|C#]] constructor:
 
Line 233 ⟶ 137:
 
==== C# static constructor ====
In [[C Sharp (programming language)|C#]], a ''static constructor'' is a static data initializer.<ref name="Albahari">{{cite book |last=Albahari |first=Joseph |title= C# 10 in a Nutshell |publisher= O'Reilly |isbn= 978-1-098-12195-2}}</ref>{{rp|111-112}} Static constructors are also called ''class constructors''. Since the actual method generated has the name ''.cctor'' they are often also called "cctors".<ref>{{cite web|url=http://ericlippert.com/2013/02/06/static-constructors-part-one/ |title=Fabulous Adventures in Coding |publisher=Eric Lippert |date=2013-02-06|access-date=2014-04-05}}</ref><ref>{{cite book|url=https://books.google.com/books?id=oAcCRKd6EZgC&pg=PA222 |title=Expert .NET 2.0 IL Assembler |publisher=APress |date=2006-01-01|isbn=9781430202233 |access-date=2014-04-05}}</ref>
 
Static constructors allow complex static variable initialization.<ref>{{Cite web|url=https://www.microsoft.com/en-us/download/details.aspx?id=55984|title=Download Visual Studio 2005 Retired documentation from Official Microsoft Download Center|website=Microsoft Store - Download Center}}</ref>
In [[C Sharp (programming language)|C#]], a ''static constructor'' is a static data initializer. Static constructors are also called ''class constructors''. Since the actual method generated has the name ''.cctor'' they are often also called "cctors".<ref>{{cite web|url=http://ericlippert.com/2013/02/06/static-constructors-part-one/ |title=Fabulous Adventures in Coding |publisher=Eric Lippert |date=2013-02-06|accessdate=2014-04-05}}</ref><ref>{{cite book|url=https://books.google.com/books?id=oAcCRKd6EZgC&pg=PA222 |title=Expert .NET 2.0 IL Assembler |publisher=APress |date=2006-01-01|accessdate=2014-04-05}}</ref>
 
Static constructors allow complex static variable initialization.<ref>[http://msdn.microsoft.com/en-us/library/k9x6w0hc%28VS.80%29.aspx Static Constructor in C# on MSDN]</ref>
Static constructors are called implicitly when the class is first accessed. Any call to a class (static or constructor call), triggers the static constructor execution.
Static constructors are [[thread safe]] and implement a [[singleton pattern]]. When used in a [[generic programming]] class, static constructors are called at every new generic instantiation one per type.<ref name=Skeet>{{cite book |last=Skeet|first=Jon|title= C# in Depth |date=23 March 2019 |publisher= Manning |isbn= 978-1617294532}}</ref>{{rp|38}}<ref name="Albahari"/>{{rp|111}} Static variables are instantiated as well.
 
<syntaxhighlight lang="csharp">
Line 267 ⟶ 170:
</syntaxhighlight>
 
=== ColdFusion Markup Language (CFML) ===
=== C++ ===
[[ColdFusion Markup Language]] (CFML) uses a method named '<code>init</code>' as a constructor method.
 
'''Cheese.cfc'''
In [[C++]], the name of the constructor is the name of the class. It returns nothing. It can have parameters like any [[Method (computer programming)|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.
<syntaxhighlight lang="cfc">
component {
// properties
property name="cheeseName";
 
// constructor
The constructor has two parts. First is the [[initializer list]] which follows the [[parameter (computer science)|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 you have ''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).<ref>https://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order Constructor</ref> The second part is the body, which is a normal method body enclosed in curly brackets.
function Cheese init( required string cheeseName ) {
variables.cheeseName = arguments.cheeseName;
return this;
}
}
</syntaxhighlight>
 
Create instance of a cheese.
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.
<syntaxhighlight lang="cfc">
 
myCheese = new Cheese( 'Cheddar' );
A copy constructor has a parameter of the same type passed as ''const'' reference, for example ''Vector(const Vector& 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.
 
<syntaxhighlight lang="cpp">
class Foobar {
public:
Foobar(double r = 1.0,
double alpha = 0.0) // Constructor, parameters with default values.
: x_(r * cos(alpha)) // <- Initializer list
{
y_ = r * sin(alpha); // <- Normal assignment
}
 
private:
double x_;
double y_;
};
</syntaxhighlight>
Example invocations:
<syntaxhighlight lang="cpp">
Foobar a,
b(3),
c(5, M_PI/4);
</syntaxhighlight>
 
Since ColdFusion 10,<ref>[https://wikidocs.adobe.com/wiki/display/coldfusionen/cfcomponent CFComponent]</ref> CFML has also supported specifying the name of the constructor method:
On returning objects from functions or passing objects by value, the objects copy constructor will be called implicitly, unless [[return value optimization]] applies.
 
<syntaxhighlight lang="cfc">
C++ implicitly generates a default copy constructor which will call the copy constructors for all base classes and all member variables unless the programmer provides one, explicitly deletes the copy constructor (to prevent cloning) or one of the base classes or member variables copy constructor is deleted or not accessible (private). Most cases calling for a customized '''copy constructor''' (e.g. [[reference counting]], [[deep copy]] of pointers) also require customizing the '''destructor''' and the '''copy assignment operator'''. This is commonly referred to as the [[Rule of three (C++ programming)|Rule of three]].
component initmethod="Cheese" {
// properties
property name="cheeseName";
 
// constructor
=== F# ===
function Cheese Cheese( required string cheeseName ) {
 
variables.cheeseName = arguments.cheeseName;
In [[F Sharp (programming language)|F#]], a constructor can include any <code>let</code> or <code>do</code> statements defined in a class. <code>let</code> statements define private fields and <code>do</code> statements execute code. Additional constructors can be defined using the <code>new</code> keyword.
return this;
 
}
<syntaxhighlight lang="fsharp">
}
type MyClass(_a : int, _b : string) = class
// Primary constructor
let a = _a
let b = _b
do printfn "a = %i, b = %s" a b
 
// Additional constructors
new(_a : int) = MyClass(_a, "") then
printfn "Integer parameter given"
 
new(_b : string) = MyClass(0, _b) then
printfn "String parameter given"
 
new() = MyClass(0, "") then
printfn "No parameter given"
end
</syntaxhighlight>
 
<syntaxhighlight lang = "fsharp">
// Code somewhere
// instantiating an object with the primary constructor
let c1 = new MyClass(42, "string")
 
// instantiating an object with additional constructors
let c2 = new MyClass(42)
let c3 = new MyClass("string")
let c4 = MyClass() // "new" keyword is optional
</syntaxhighlight>
 
=== Eiffel ===
 
In [[Eiffel (programming language)|Eiffel]], the routines which initialize new objects are called ''creation procedures''. Creation procedures have the following traits:
 
Line 348 ⟶ 217:
* Creation procedures must leave the newly initialized object in a state that satisfies the class invariant.{{Efn|Because the inherited class invariant must be satisfied, there is no mandatory call to the parents' constructors.}}
 
Although object creation involves some subtleties,<ref name="eiffel standard">[{{Cite web|url=http://www.ecma-international.org/publications/standards/Ecma-367.htm |title=Eiffel ISO/ECMA specification document]}}</ref> the creation of an attribute with a typical declaration <code lang="eiffel">x: T</code> as expressed in a creation instruction <code lang="eiffel">create x.make</code> consists of the following sequence of steps:
 
* Create a new direct instance of type <code lang="eiffel">T</code>.{{Efn|The Eiffel standard requires fields to be initialized on first access, so it is not necessary to perform default field initialization during object creation.}}
Line 398 ⟶ 267:
</syntaxhighlight>
 
=== CFMLF# ===
In [[F Sharp (programming language)|F#]], a constructor can include any <code>let</code> or <code>do</code> statements defined in a class. <code>let</code> statements define private fields and <code>do</code> statements execute code. Additional constructors can be defined using the <code>new</code> keyword.
 
<syntaxhighlight lang="fsharp">
[[CFML]] uses a method named '<code>init</code>' as a constructor method.
type MyClass(_a : int, _b : string) = class
// Primary constructor
let a = _a
let b = _b
do printfn "a = %i, b = %s" a b
 
// Additional constructors
'''Cheese.cfc'''
new(_a : int) = MyClass(_a, "") then
<syntaxhighlight lang="javascript">
printfn "Integer parameter given"
component {
// properties
property name="cheeseName";
 
new(_b : string) = MyClass(0, _b) then
// constructor
printfn "String parameter given"
function Cheese init( required string cheeseName ) {
 
variables.cheeseName = arguments.cheeseName;
new() = returnMyClass(0, this;"") then
printfn "No parameter given"
}
end
</syntaxhighlight>
 
<syntaxhighlight lang = "fsharp">
// Code somewhere
// instantiating an object with the primary constructor
let c1 = new MyClass(42, "string")
 
// instantiating an object with additional constructors
let c2 = new MyClass(42)
let c3 = new MyClass("string")
let c4 = MyClass() // "new" keyword is optional
</syntaxhighlight>
 
=== Java ===
In [[Java (programming language)|Java]], constructors differ from other methods in that:
 
* Constructors never have an explicit return type.
* Constructors cannot be directly invoked (the keyword “<code>new</code>” invokes them).
* Constructors should not have non-access modifiers.
 
Java constructors perform the following tasks in the following order:
 
# Call the default constructor of the superclass if no constructor is defined.
# Initialize member variables to the specified values.
# Executes the body of the constructor.
 
Java permit users to call one constructor in another constructor using <code>this()</code> keyword.
But <code>this()</code> must be first statement. <ref>{{Cite web|url=https://ranjeetkumarmaurya.wordpress.com/2017/02/06/constructor-in-java/|title=Details on Constructor in java}}</ref>
 
<syntaxhighlight lang="java">
class X {
public X() { // Non-parameterized constructor
this(1); // Calling of constructor
System.out.println("Calling default constructor");
}
 
public X(int a) { // Parameterized constructor
System.out.println("Calling parameterized constructor");
}
}
 
public class Example {
public static void main(String[] args) {
X x = new X();
}
}
</syntaxhighlight>
 
Java provides access to the [[superclass (computer science)|superclass's]] constructor through the <code>super</code> keyword.
Create instance of a cheese.
 
<syntaxhighlight lang="java">
class X {
// Declaration of instance variable(s).
private int data;
 
// Definition of the constructor.
public X() {
this(1);
}
 
// Overloading a constructor
public X(int input) {
data = input; // This is an assignment
}
}
 
class Y extends X {
private int data2;
 
public Y() {
super();
data2 = 1;
}
 
public Y(int input1, int input2) {
super(input1);
data2 = input2
}
}
 
public class Example {
public static void main(String[] args) {
Y y = new Y(42, 43);
}
}
</syntaxhighlight>
 
A constructor taking zero number of arguments is called a "no-arguments" or "no-arg" constructor.<ref>{{cite web|url=http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html|title= Providing Constructors for Your Classes |publisher=Oracle Corporation|date=2013|access-date=2013-12-20}}</ref>
 
=== JavaScript/TypeScript ===
As of ES6, [[JavaScript]] has direct constructors like many other programming languages. They are written as such
 
<syntaxhighlight lang="javascript">
class FooBar {
myCheese = new Cheese( 'Cheddar' );
constructor(baz) {
this.baz = baz;
}
}
</syntaxhighlight>
 
This can be instantiated as such
Since ColdFusion 10,<ref>[https://wikidocs.adobe.com/wiki/display/coldfusionen/cfcomponent CFComponent]</ref> CFML has also supported specifying the name of the constructor method:
 
<syntaxhighlight lang="javascript">
const foo = new FooBar('7');
component initmethod="Cheese" {
</syntaxhighlight>
// properties
property name="cheeseName";
 
The equivalent of this before ES6, was creating a function that instantiates an object as such
// constructor
 
function Cheese Cheese( required string cheeseName ) {
<syntaxhighlight lang="javascript">
variables.cheeseName = arguments.cheeseName;
function FooBar (baz) {
return this;
this.baz = baz;
}
}
</syntaxhighlight>
 
This is instantiated the same way as above.
=== Object Pascal ===
 
The [[TypeScript]] equivalent of this would be:
<syntaxhighlight lang="typescript">
class FooBar {
baz: string;
 
constructor(baz: string) {
this.baz = baz;
}
}
 
const foo: FooBar = new FooBar('7');
</syntaxhighlight>
 
=== Object Pascal ===
In [[Object Pascal]], the constructor is similar to a [[factory method]]. The only syntactic difference to regular methods is the keyword <code>constructor</code> in front of the name (instead of <code>procedure</code> or <code>function</code>). It can have any name, though the convention is to have <code>Create</code> as prefix, such as in <code>CreateWithFormatting</code>. Creating an instance of a class works like calling a static method of a class: <code>TPerson.Create('Peter')</code>.
 
Line 464 ⟶ 443:
</syntaxhighlight>
 
=== Perl 5OCaml ===
In [[OCaml]], there is one constructor. Parameters are defined right after the class name. They can be used to initialize instance variables and are accessible throughout the class. An anonymous hidden method called <code>initializer</code> allows to evaluate an expression immediately after the object has been built.<ref>{{Cite web|url=https://ocaml.org/manual/5.3/index.html|title=OCaml - The OCaml Manual|website=ocaml.org}}</ref>
 
<syntaxhighlight lang="ocaml">
In [[Perl|Perl programming language]] version 5, by default, constructors are [[factory method]]s, that is, methods that create and return the object, concretely meaning create and return a blessed reference. A typical object is a reference to a hash, though rarely references to other types are used too. By convention the only constructor is named ''new'', though it is allowed to name it otherwise, or to have multiple constructors. For example, a Person class may have a constructor named ''new'' as well as a constructor ''new_from_file'' which reads a file for Person attributes, and ''new_from_person'' which uses another Person object as a template.
class person first_name last_name =
object
val full_name = first_name ^ " " ^ last_name
 
initializer
print_endline("Hello there, I am " ^ full_name ^ ".")
 
method get_last_name = last_name
end;;
 
let alonzo = new person "Alonzo" "Church" in (*Hello there, I am Alonzo Church.*)
 
print_endline alonzo#get_last_name (*Church*)
</syntaxhighlight>
 
=== PHP ===
In [[PHP]] version 5 and above, the constructor is a method named <code>__construct()</code> (notice that it's a double underscore), which the keyword <code>new</code> automatically calls after creating the object. It is usually used to automatically perform initializations such as property initializations. Constructors can also accept arguments, in which case, when the <code>new</code> statement is written, you also need to send the constructor arguments for the parameters.<ref name="php5cpnstructor"/>
 
<syntaxhighlight lang="php">
class Person
{
private string $name;
 
public function __construct(string $name): void
{
$this->name = $name;
}
 
public function getName(): string
{
return $this->name;
}
}
</syntaxhighlight>
 
In PHP, a class is only allowed to declare a maximum of one constructor method. Static methods, factory classes or optional constructor arguments are some ways to facilitate multiple ways to create objects of a PHP class.
 
=== Perl 5 ===
In [[Perl]] version 5, by default, constructors are [[factory method]]s, that is, methods that create and return the object, concretely meaning create and return a blessed reference. A typical object is a reference to a hash, though rarely references to other types are used too. By convention the only constructor is named ''new'', though it is allowed to name it otherwise, or to have multiple constructors. For example, a Person class may have a constructor named ''new'', and a constructor ''new_from_file'' which reads a file for Person attributes, and ''new_from_person'' which uses another Person object as a template.
 
<syntaxhighlight lang="perl">
Line 499 ⟶ 518:
</syntaxhighlight>
 
==== Perl 5 with Moose ====
In the [[Moose perl|Moose object system]] for Perl, most of this boilerplate can be omitted, a default ''new'' is created, attributes can be specified, and whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a ''BUILD'' method which the Moose generated constructor will call, after it has checked the arguments. A ''BUILDARGS'' method can be specified to handle constructor arguments not in hashref / key => value form.
 
With the [[Moose perl|Moose object system]] for Perl, most of this boilerplate can be left out, a default ''new'' is created, attributes can be specified, as well as whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a ''BUILD'' method which the Moose generated constructor will call, after it has checked the arguments. A ''BUILDARGS'' method can be specified to handle constructor arguments not in hashref / key => value form.
 
<syntaxhighlight lang="perl">
Line 533 ⟶ 551:
</syntaxhighlight>
 
=== Perl 6Python ===
In [[Python (programming language)|Python]], constructors are defined by one or both of <code>__new__</code> and <code>__init__</code> methods. A new instance is created by calling the class as if it were a function, which calls the <code>__new__</code> and <code>__init__</code> methods. If a constructor method is not defined in the class, the next one found in the class's Method Resolution Order will be called.<ref name="auto">{{Cite web|url=https://docs.python.org/3/reference/datamodel.html|title=3. Data model|website=Python documentation}}</ref>
 
In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.)
 
<syntaxhighlight lang="python">
class ExampleClass:
def __new__(cls: type, value: int) -> 'ExampleClass':
print("Creating new instance...")
# Call the superclass constructor to create the instance.
instance: 'ExampleClass' = super(ExampleClass, cls).__new__(cls)
return instance
 
def __init__(self, value: int) -> None:
print("Initialising instance...")
self.payload: int = value
 
if __name__ == "__main__":
exampleInstance: ExampleClass = ExampleClass(42)
print(exampleInstance.payload)
</syntaxhighlight>
 
This prints:
<pre>
Creating new instance...
Initialising instance...
42
</pre>
 
Classes normally act as [[Factory (object-oriented programming)|factories]] for new instances of themselves, that is, a class is a callable object (like a function), with the call being the constructor, and calling the class returns an instance of that class. However the <code>__new__</code> method is permitted to return something other than an instance of the class for specialised purposes. In that case, the <code>__init__</code> is not invoked.<ref name="auto"/>
 
=== Raku ===
With Perl 6, even more boilerplate can be left out, given that a default ''new'' method is inherited, attributes can be specified, as well as whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a ''BUILD'' method which will get called to allow for custom initialization. A ''TWEAK'' method can be specified to post-process any attributes already (implicitly) initialized.
In [[Raku (programming language)|Raku]], even more boilerplate can be omitted, given that a default ''new'' method is inherited, attributes can be specified, and whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a ''BUILD'' method which will get called to allow for custom initialization. A ''TWEAK'' method can be specified to post-process any attributes already (implicitly) initialized.
 
<syntaxhighlight lang="perl6">
Line 572 ⟶ 620:
</syntaxhighlight>
 
Alternatively, the [[named parametersparameter]]s can be specified using the colon-pair syntax in Perl 6:
<syntaxhighlight lang="perl6">
my $p0 = Person.new( :first-name<Sam>, :last-name<Ashe>, :age(42) );
Line 585 ⟶ 633:
my $p0 = Person.new( :$first-name, :$last-name, :$age );
</syntaxhighlight>
 
=== PHP ===
 
In [[PHP]] version 5 and above, the constructor is a method named <code>__construct()</code> (notice that it's a double underscore), which the keyword <code>new</code> automatically calls after creating the object. It is usually used to automatically perform initializations such as property initializations. Constructors can also accept arguments, in which case, when the <code>new</code> statement is written, you also need to send the constructor arguments for the parameters.<ref name="php5cpnstructor"/>
 
<syntaxhighlight lang="php">
class Person
{
private string $name;
 
public function __construct(string $name) : void
{
$this->name = $name;
}
 
public function getName() : string
{
return $this->name;
}
}
</syntaxhighlight>
 
=== Python ===
 
In [[Python (programming language)|Python]], constructors are defined by one or both of <code>__new__</code> and <code>__init__</code> methods. A new instance is created by calling the class as if it were a function, which calls the <code>__new__</code> and <code>__init__</code> methods. If a constructor method is not defined in the class, the next one found in the class's [[C3 linearization|Method Resolution Order]] will be called.<ref>[https://docs.python.org/3/reference/datamodel.html Data model]</ref>
 
In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.)
 
<syntaxhighlight lang="pycon">
>>> class ExampleClass(object):
... def __new__(cls, value):
... print("Creating new instance...")
... # Call the superclass constructor to create the instance.
... instance = super(ExampleClass, cls).__new__(cls)
... return instance
... def __init__(self, value):
... print("Initialising instance...")
... self.payload = value
>>> exampleInstance = ExampleClass(42)
Creating new instance...
Initialising instance...
>>> print(exampleInstance.payload)
42
</syntaxhighlight>
 
Classes normally act as [[Factory (object-oriented programming)|factories]] for new instances of themselves, that is, a class is a callable object (like a function), with the call being the constructor, and calling the class returns an instance of that class. However the <code>__new__</code> method is permitted to return something other than an instance of the class for specialised purposes. In that case, the <code>__init__</code> is not invoked.<ref>[https://docs.python.org/3/reference/datamodel.html#object.__new__ Data model]</ref>
 
=== Ruby ===
 
In [[Ruby (programming language)|Ruby]], constructors are created by defining a method called <code>initialize</code>. This method is executed to initialize each new instance.
<syntaxhighlight lang="rbcon">
Line 647 ⟶ 648:
</syntaxhighlight>
 
=== OCamlRust ===
[[Rust (programming language)|Rust]] does not have constructors in the sense of object-oriented programming, but often structs have a <code>new()</code> method that essentially acts as a constructor. The return type is usually indicated as <code>Self</code>.
 
<syntaxhighlight lang="rust">
In [[OCaml (programming language)|OCaml]], there is one constructor. Parameters are defined right after the class name. They can be used to initialize instance variables and are accessible throughout the class. An anonymous hidden method called <code>initializer</code> allows to evaluate an expression immediately after the object has been built.
struct Point {
<ref>[http://caml.inria.fr/pub/docs/manual-ocaml/index.html OCaml manual]</ref>
x: i32,
y: i32,
}
 
impl Point {
<syntaxhighlight lang="ocaml">
pub fn new(x: i32, y: i32) -> Self {
class person first_name last_name =
Point { x, y }
object
}
val full_name = first_name ^ " " ^ last_name
}
 
fn main() {
initializer
let p: Point = Point::new(10, 20);
print_endline("Hello there, I am " ^ full_name ^ ".")
println!("Point is at ({}, {})", p.x, p.y);
}
</syntaxhighlight>
 
=== Visual Basic .NET ===
method get_last_name = last_name
In [[Visual Basic .NET]], constructors use a method declaration with the name "<code>New</code>".
end;;
 
<syntaxhighlight lang="vbnet">
let alonzo = new person "Alonzo" "Church" in (*Hello there, I am Alonzo Church.*)
Class Foobar
Private strData As String
 
' Constructor
print_endline alonzo#get_last_name (*Church*)
Public Sub New(ByVal someParam As String)
strData = someParam
End Sub
End Class
</syntaxhighlight>
 
<syntaxhighlight lang="vbnet">
' code somewhere else
' instantiating an object with the above constructor
Dim foo As New Foobar(".NET")
</syntaxhighlight>
 
== See also ==
* [[Resource acquisition is initialization]] (RAII)
* [[Allocation site]]
* [[Creational pattern]]
* [[Destructor (computer scienceprogramming)|Destructor]]
* [[Global constructor]] in C++, and its C counterpart, [[((constructor))]] function attribute