Revision as of 12:39, 2 February 2021 edit41.38.212.12 (talk) →C# static constructor: accessTag: Reverted← Previous edit | Latest revision as of 15:16, 21 December 2024 edit undoApokrif (talk | contribs)Extended confirmed users, Pending changes reviewers28,380 editsm →Default constructors: Wkf. | ||
(30 intermediate revisions by 25 users not shown) | |||
Line 1: | Line 1: | ||
{{Short description|Special function called to create an object}} | |||
{{ProgLangCompare}} | {{ProgLangCompare}} | ||
In ] ], a '''constructor''' (abbreviation: '''ctor''') is a special type of ] called to ]. It prepares the new object for use, often accepting ] that the constructor uses to set required ]s. | |||
A constructor resembles an ], but it differs from a method in that it has no explicit ], it is not implicitly ] and it usually has different rules for scope modifiers. Constructors often have the same name as the declaring ]. They have the task of ] the object's ]s and of establishing the ], failing if the invariant is invalid. A properly written constructor leaves the resulting ] in a ''valid'' state. ]s must be initialized in a constructor. | In ], ], a '''constructor''' (abbreviation: '''ctor''') is a special type of ] called to ]. It prepares the new object for use, often accepting ] that the constructor uses to set required ]s. | ||
A constructor resembles an ], but it differs from a method in that it has no explicit ], it is not implicitly ] and it usually has different rules for scope modifiers. Constructors often have the same name as the declaring ]. They have the task of ] the object's ]s and of establishing the ], failing if the invariant is invalid. A properly written constructor leaves the resulting ] in a ''valid'' state. ]s must be initialized in a constructor. | |||
Most languages allow ] 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 ], which also create objects but can do so in various ways, using multiple classes or different allocation schemes such as an ]. | Most languages allow ] 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 ], which also create objects but can do so in various ways, using multiple classes or different allocation schemes such as an ]. | ||
== Types == | == Types == | ||
=== Parameterized constructors === | === 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"> | <syntaxhighlight lang="cpp"> | ||
Line 35: | Line 34: | ||
=== Default constructors === | === Default constructors === | ||
If the programmer does not supply a constructor for an instantiable class, Java compiler inserts a ] 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'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). | If the programmer does not supply a constructor for an instantiable class, Java compiler inserts a ] 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 ]'s ] 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"> | <syntaxhighlight lang="cpp"> | ||
Line 52: | Line 51: | ||
{{see also|Copy constructor (C++)}} | {{see also|Copy constructor (C++)}} | ||
Like C++, Java also supports "Copy Constructor". But, unlike C++, Java doesn't create a default copy constructor if you don'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. | Like C++, Java also supports "Copy Constructor". But, unlike C++, Java doesn't create a default copy constructor if you don'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. | While copy constructors are usually abbreviated copy ctor or cctor, they have nothing to do with class constructors used in ] using the same abbreviation. | ||
=== Conversion constructors === | === 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. | 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 === | === Move constructors === | ||
In C++, ] 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++, ] take a value reference to an object of the class, and are used to implement ownership transfer of the parameter object's resources. | |||
== Syntax == | == Syntax == | ||
* ], ], ], ], {{nowrap|] 4}} and ] have a naming convention in which constructors have the same name as the class with which they are associated. | * ], ], ], ], {{nowrap|] 4}} and ] have a naming convention in which constructors have the same name as the class with which they are associated. | ||
* 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">, from PHP online documentation</ref> | * 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">, from PHP online documentation</ref> | ||
Line 75: | Line 71: | ||
== Memory organization == | == Memory organization == | ||
In Java, C#, and VB .NET, the constructor creates reference type objects in a special memory structure called the | In Java, C#, and VB .NET, the constructor creates reference type objects in a special memory structure called the | ||
"]". Value types (such as int, double, etc.) are created in a sequential structure called the "]". | "]". Value types (such as int, double, etc.) are created in a sequential structure called the "]". | ||
Line 82: | Line 77: | ||
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. | 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. | ||
== Language details == | == Language details ==<!-- see also Category:Programming language comparisons --> | ||
Constructors are implemented in different ]s in various ways, including: | |||
=== C++ === | |||
{{Split|Comparison of programming languages (OOP, constructors)|date=May 2016}} <!-- see also Category:Programming language comparisons --> | |||
In ], the name of the constructor is the name of the class. It returns nothing. It can have parameters like any ]. 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 ] which follows the ] 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. | |||
=== Java === | |||
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 ] (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. | |||
In ], constructors differ from other methods in that: | |||
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. | |||
* Constructors never have an explicit return type. | |||
* 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 | |||
<syntaxhighlight lang="cpp"> | |||
Java constructors perform the following tasks in the following order: | |||
class Foobar { | |||
public: | |||
# Call the default constructor of the superclass if no constructor is defined. | |||
Foobar(double r = 1.0, | |||
# Initialize member variables to the specified values. | |||
double alpha = 0.0) // Constructor, parameters with default values. | |||
# Executes the body of the constructor. | |||
: x_(r * cos(alpha)) // <- Initializer list | |||
{ | |||
Java permit users to call one constructor in another constructor using <code>this()</code> keyword. | |||
y_ = r * sin(alpha); // <- Normal assignment | |||
But <code>this()</code> must be first statement. <ref></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> | |||
Java provides access to the ] constructor through the <code>super</code> keyword. | |||
<syntaxhighlight lang="java"> | |||
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> | |||
<syntaxhighlight lang="java"> | |||
// Code somewhere else | |||
// Instantiating an object with the above constructor | |||
Example e = new Example(42); | |||
</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 === | |||
As of ES6, ] has direct constructors like many other programming languages. They are written as such | |||
<syntaxhighlight lang="javascript"> | |||
class FooBar { | |||
constructor(baz) { | |||
this.baz = baz | |||
} | } | ||
} | |||
</syntaxhighlight> | |||
private: | |||
This can be instantiated as such | |||
double x_; | |||
double y_; | |||
<syntaxhighlight lang="javascript"> | |||
}; | |||
const foo = new FooBar('7') | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Example invocations: | |||
<syntaxhighlight lang="cpp"> | |||
The equivalent of this before ES6, was creating a function that instantiates an object as such | |||
Foobar a, | |||
b(3), | |||
<syntaxhighlight lang="javascript"> | |||
c(5, M_PI/4); | |||
function FooBar (baz) { | |||
this.baz = baz; | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
On returning objects from functions or passing objects by value, the objects copy constructor will be called implicitly, unless ] applies. | |||
This is instantiated the same way as above. | |||
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. ], ] of pointers) also require customizing the '''destructor''' and the '''copy assignment operator'''. This is commonly referred to as the ]. | |||
=== Visual Basic .NET === | |||
In ], 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# === | === C# === | ||
Example ] constructor: | Example ] constructor: | ||
Line 233: | Line 145: | ||
==== C# static constructor ==== | ==== C# static constructor ==== | ||
In ], 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> | |||
In ], 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|-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=20060=1=1|isbn=9781430202233 |access-date=21094-04-05}}</ref> | |||
Static constructors allow complex static variable initialization.<ref></ref> | Static constructors allow complex static variable initialization.<ref></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 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 ] and implement a ]. When used in a ] class, static constructors are called at every new generic instantiation one per type. Static variables are instantiated as well. | Static constructors are ] and implement a ]. When used in a ] 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 |publisher= Manning |isbn= 978-1617294532}}</ref>{{rp|38}}<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}} Static variables are instantiated as well. | ||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
public class MyClass | public class MyClass | ||
{ | { | ||
private static int |
private static int _A; | ||
// Normal constructor | // Normal constructor | ||
Line 267: | Line 178: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== ColdFusion Markup Language (CFML) === | |||
=== C++ === | |||
] (CFML) uses a method named '<code>init</code>' as a constructor method. | |||
'''Cheese.cfc''' | |||
In ], the name of the constructor is the name of the class. It returns nothing. It can have parameters like any ]. 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="javascript"> | |||
component { | |||
// properties | |||
property name="cheeseName"; | |||
// constructor | |||
The constructor has two parts. First is the ] which follows the ] 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 ] (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="javascript"> | |||
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> | </syntaxhighlight> | ||
Since ColdFusion 10,<ref></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 ] applies. | |||
<syntaxhighlight lang="javascript"> | |||
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. ], ] of pointers) also require customizing the '''destructor''' and the '''copy assignment operator'''. This is commonly referred to as the ]. | |||
component initmethod="Cheese" { | |||
// properties | |||
property name="cheeseName"; | |||
// constructor | |||
=== F# === | |||
function Cheese Cheese( required string cheeseName ) { | |||
variables.cheeseName = arguments.cheeseName; | |||
In ], 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> | </syntaxhighlight> | ||
=== Eiffel === | === Eiffel === | ||
In ], the routines which initialize new objects are called ''creation procedures''. Creation procedures have the following traits: | In ], the routines which initialize new objects are called ''creation procedures''. Creation procedures have the following traits: | ||
Line 398: | Line 275: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== |
=== F# === | ||
In ], 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"> | |||
] 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() = 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> | |||
=== Java === | |||
In ], 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></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> | </syntaxhighlight> | ||
Java provides access to the ] constructor through the <code>super</code> keyword. | |||
Create instance of a cheese. | |||
<syntaxhighlight lang="java"> | |||
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> | |||
<syntaxhighlight lang="java"> | |||
// Code somewhere else | |||
// Instantiating an object with the above constructor | |||
Example e = new Example(42); | |||
</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 === | |||
As of ES6, ] has direct constructors like many other programming languages. They are written as such | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
class FooBar { | |||
myCheese = new Cheese( 'Cheddar' ); | |||
constructor(baz) { | |||
this.baz = baz | |||
} | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
This can be instantiated as such | |||
Since ColdFusion 10,<ref></ref> CFML has also supported specifying the name of the constructor method: | |||
<syntaxhighlight lang="javascript"> | <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> | </syntaxhighlight> | ||
This is instantiated the same way as above. | |||
=== Object Pascal === | |||
=== Object Pascal === | |||
In ], the constructor is similar to a ]. 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>. | In ], the constructor is similar to a ]. 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: | Line 427: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== |
=== OCaml === | ||
In ], 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></ref> | |||
<syntaxhighlight lang="ocaml"> | |||
In ] version 5, by default, constructors are ]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 ] 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 ] version 5, by default, constructors are ]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"> | <syntaxhighlight lang="perl"> | ||
Line 499: | Line 502: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== Perl 5 with Moose === | ==== Perl 5 with Moose ==== | ||
In the ] 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 ] 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"> | <syntaxhighlight lang="perl"> | ||
Line 533: | Line 535: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== |
=== Python === | ||
In ], 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 ] will be called.<ref></ref> | |||
In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.) | |||
With ], 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. | |||
<syntaxhighlight lang="pycon"> | |||
>>> class ExampleClass: | |||
... 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 ] 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></ref> | |||
=== Raku === | |||
In ], 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"> | <syntaxhighlight lang="perl6"> | ||
Line 572: | Line 597: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Alternatively, the named |
Alternatively, the ]s can be specified using the colon-pair syntax in Perl 6: | ||
<syntaxhighlight lang="perl6"> | <syntaxhighlight lang="perl6"> | ||
my $p0 = Person.new( :first-name<Sam>, :last-name<Ashe>, :age(42) ); | my $p0 = Person.new( :first-name<Sam>, :last-name<Ashe>, :age(42) ); | ||
Line 585: | Line 610: | ||
my $p0 = Person.new( :$first-name, :$last-name, :$age ); | my $p0 = Person.new( :$first-name, :$last-name, :$age ); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== PHP === | |||
In ] 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 ], 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 ] will be called.<ref></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: | |||
... 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 ] 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></ref> | |||
=== Ruby === | === Ruby === | ||
In ], constructors are created by defining a method called <code>initialize</code>. This method is executed to initialize each new instance. | In ], constructors are created by defining a method called <code>initialize</code>. This method is executed to initialize each new instance. | ||
<syntaxhighlight lang="rbcon"> | <syntaxhighlight lang="rbcon"> | ||
Line 647: | Line 625: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== |
=== Visual Basic .NET === | ||
In ], constructors use a method declaration with the name "<code>New</code>". | |||
<syntaxhighlight lang="vbnet"> | |||
In ], 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. | |||
Class Foobar | |||
<ref></ref> | |||
Private strData As String | |||
' Constructor | |||
<syntaxhighlight lang="ocaml"> | |||
Public Sub New(ByVal someParam As String) | |||
class person first_name last_name = | |||
strData = someParam | |||
object | |||
End Sub | |||
val full_name = first_name ^ " " ^ last_name | |||
End Class | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="vbnet"> | |||
initializer | |||
' code somewhere else | |||
print_endline("Hello there, I am " ^ full_name ^ ".") | |||
' instantiating an object with the above constructor | |||
Dim foo As New Foobar(".NET") | |||
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> | </syntaxhighlight> | ||
== See also == | == See also == | ||
* ] (RAII) | |||
* ] | * ] | ||
* ] | * ] | ||
* ] | * ] | ||
* ] in C++, and its C counterpart, ] function attribute | * ] in C++, and its C counterpart, ] function attribute | ||
Latest revision as of 15:16, 21 December 2024
Special function called to create an objectIn 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 Example { public: Example(); Example(int a, int b); // Parameterized constructor. private: int x_; int y_; }; Example::Example() = default; Example::Example(int x, int y) : x_(x), y_(y) {}
Example e = Example(0, 50); // Explicit call. Example e2(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 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'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)...
#include <iostream> class Student { public: Student(int a = 0, int b = 0); // Default constructor. int a; int b; };
Copy constructors
See also: Copy constructor (C++)Like C++, Java also supports "Copy Constructor". But, unlike C++, Java doesn't create a default copy constructor if you don'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 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, PHP 4 and MATLAB have a naming convention in which constructors have the same name as the class with which they are associated.
- 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. - 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
"). - 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 thealloc
method setting aside (allocating) memory for an instance of the class, and theinit
method handling the bulk of initializing the instance. A call to the method "new
" invokes both thealloc
and theinit
methods, for the class instance.
Memory organization
In Java, C#, and VB .NET, the constructor creates reference type objects in a special memory structure called the "heap". Value types (such as int, double, etc.) are created in a sequential structure called the "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.
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.
Language details
Constructors are implemented in different programming languages in various ways, including:
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 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). The second part is the body, which is a normal method body enclosed in curly brackets.
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 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.
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_; };
Example invocations:
Foobar a, b(3), c(5, M_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.
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#
Example C# constructor:
public class MyClass { private int a; private string b; // Constructor public MyClass() : this(42, "string") { } // Overloading a constructor public MyClass(int a, string b) { this.a = a; this.b = b; } }
// Code somewhere // Instantiating an object with the constructor above MyClass c = new MyClass(42, "string");
C# static constructor
In 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".
Static constructors allow complex static variable initialization. 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. Static variables are instantiated as well.
public class MyClass { private static int _A; // Normal constructor static MyClass() { _A = 32; } // Standard default constructor public MyClass() { } }
// Code somewhere // Instantiating an object with the constructor above // right before the instantiation // The variable static constructor is executed and _A is 32 MyClass c = new MyClass();
ColdFusion Markup Language (CFML)
ColdFusion Markup Language (CFML) uses a method named 'init
' as a constructor method.
Cheese.cfc
component { // properties property name="cheeseName"; // constructor function Cheese init( required string cheeseName ) { variables.cheeseName = arguments.cheeseName; return this; } }
Create instance of a cheese.
myCheese = new Cheese( 'Cheddar' );
Since ColdFusion 10, CFML has also supported specifying the name of the constructor method:
component initmethod="Cheese" { // properties property name="cheeseName"; // constructor function Cheese Cheese( required string cheeseName ) { variables.cheeseName = arguments.cheeseName; return this; } }
Eiffel
In Eiffel, the routines which initialize new objects are called creation procedures. Creation procedures have the following traits:
- Creation procedures have no explicit return type (by definition of procedure).
- Creation procedures are named.
- Creation procedures are designated by name as creation procedures in the text of the class.
- Creation procedures can be explicitly invoked to re-initialize existing objects.
- Every effective (i.e., concrete or non-abstract) class must designate at least one creation procedure.
- Creation procedures must leave the newly initialized object in a state that satisfies the class invariant.
Although object creation involves some subtleties, the creation of an attribute with a typical declaration x: T
as expressed in a creation instruction create x.make
consists of the following sequence of steps:
- Create a new direct instance of type
T
. - Execute the creation procedure
make
to the newly created instance. - Attach the newly initialized object to the entity
x
.
In the first snippet below, class POINT
is defined. The procedure make
is coded after the keyword feature
.
The keyword create
introduces a list of procedures which can be used to initialize instances. In this case the list includes default_create
, a procedure with an empty implementation inherited from class ANY
, and the make
procedure coded within the class.
class POINT create default_create, make feature make (a_x_value: REAL; a_y_value: REAL) do x := a_x_value y := a_y_value end x: REAL -- X coordinate y: REAL -- Y coordinate ...
In the second snippet, a class which is a client to POINT
has a declarations my_point_1
and my_point_2
of type POINT
.
In procedural code, my_point_1
is created as the origin (0.0, 0.0). Because no creation procedure is specified, the procedure default_create
inherited from class ANY
is used. This line could have been coded create my_point_1.default_create
.
Only procedures named as creation procedures can be used in an instruction with the create
keyword.
Next is a creation instruction for my_point_2
, providing initial values for the my_point_2
's coordinates.
The third instruction makes an ordinary instance call to the make
procedure to reinitialize the instance attached to my_point_2
with different values.
my_point_1: POINT my_point_2: POINT ... create my_point_1 create my_point_2.make (3.0, 4.0) my_point_2.make (5.0, 8.0) ...
F#
In F#, a constructor can include any let
or do
statements defined in a class. let
statements define private fields and do
statements execute code. Additional constructors can be defined using the new
keyword.
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
// 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
Java
In Java, constructors differ from other methods in that:
- Constructors never have an explicit return type.
- Constructors cannot be directly invoked (the keyword “
new
” 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 this()
keyword.
But this()
must be first statement.
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(); }
Java provides access to the superclass's constructor through the super
keyword.
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; }
// Code somewhere else // Instantiating an object with the above constructor Example e = new Example(42);
A constructor taking zero number of arguments is called a "no-arguments" or "no-arg" constructor.
JavaScript
As of ES6, JavaScript has direct constructors like many other programming languages. They are written as such
class FooBar { constructor(baz) { this.baz = baz } }
This can be instantiated as such
const foo = new FooBar('7')
The equivalent of this before ES6, was creating a function that instantiates an object as such
function FooBar (baz) { this.baz = baz; }
This is instantiated the same way as above.
Object Pascal
In Object Pascal, the constructor is similar to a factory method. The only syntactic difference to regular methods is the keyword constructor
in front of the name (instead of procedure
or function
). It can have any name, though the convention is to have Create
as prefix, such as in CreateWithFormatting
. Creating an instance of a class works like calling a static method of a class: TPerson.Create('Peter')
.
program OopProgram; type TPerson = class private FName: string; public property Name: string read FName; constructor Create(AName: string); end; constructor TPerson.Create(AName: string); begin FName := AName; end; var Person: TPerson; begin Person := TPerson.Create('Peter'); // allocates an instance of TPerson and then calls TPerson.Create with the parameter AName = 'Peter' end.
OCaml
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 initializer
allows to evaluate an expression immediately after the object has been built.
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*)
PHP
In PHP version 5 and above, the constructor is a method named __construct()
(notice that it's a double underscore), which the keyword new
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 new
statement is written, you also need to send the constructor arguments for the parameters.
class Person { private string $name; public function __construct(string $name): void { $this->name = $name; } public function getName(): string { return $this->name; } }
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 methods, 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.
package Person; # In Perl constructors are named 'new' by convention. sub new { # Class name is implicitly passed in as 0th argument. my $class = shift; # Default attribute values, if you have any. my %defaults = ( foo => "bar" ); # Initialize attributes as a combination of default values and arguments passed. my $self = { %defaults, @_ }; # Check for required arguments, class invariant, etc. if ( not defined $self->{first_name} ) { die "Mandatory attribute missing in Person->new(): first_name"; } if ( not defined $self->{last_name} ) { die "Mandatory attribute missing in Person->new(): last_name"; } if ( defined $self->{age} and $self->{age} < 18 ) { die "Invalid attribute value in Person->new(): age < 18"; } # Perl makes an object belong to a class by 'bless'. bless $self, $class; return $self; } 1;
Perl 5 with Moose
In the 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.
package Person; # enable Moose-style object construction use Moose; # first name ( a string) can only be set at construction time ('ro') has first_name => (is => 'ro', isa => 'Str', required => 1); # last name ( a string) can only be set at construction time ('ro') has last_name => (is => 'ro', isa => 'Str', required => 1); # age (Integer) can be modified after construction ('rw'), and is not required # to be passed to be constructor. Also creates a 'has_age' method which returns # true if age has been set has age => (is => 'rw', isa => 'Int', predicate => 'has_age'); # Check custom requirements sub BUILD { my $self = shift; if ($self->has_age && $self->age < 18) { # no under 18s die "No under-18 Persons"; } } 1;
In both cases the Person class is instiated like this:
use Person; my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 );
Python
In Python, constructors are defined by one or both of __new__
and __init__
methods. A new instance is created by calling the class as if it were a function, which calls the __new__
and __init__
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.
In the typical case, only the __init__
method need be defined. (The most common exception is for immutable objects.)
>>> class ExampleClass: ... 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
Classes normally act as 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 __new__
method is permitted to return something other than an instance of the class for specialised purposes. In that case, the __init__
is not invoked.
Raku
In 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.
class Person { has Str $.first-name is required; # First name (a string) can only be set at # construction time (the . means "public"). has Str $.last-name is required; # Last name (a string) can only be set at # construction time (a ! would mean "private"). has Int $.age is rw; # Age (an integer) can be modified after # construction ('rw'), and is not required # during the object instantiation. # Create a 'full-name' method which returns the person's full name. # This method can be accessed outside the class. method full-name { $!first-name.tc ~ " " ~ $!last-name.tc } # Create a 'has-age' method which returns true if age has been set. # This method is used only inside the class so it's declared as "private" # by prepending its name with a ! method !has-age { self.age.defined } # Check custom requirements method TWEAK { if self!has-age && $!age < 18 { # No under 18 die "No person under 18"; } } }
The Person class is instantiated like this:
my $p0 = Person.new( first-name => 'Sam', last-name => 'Ashe', age => 42 ); my $p1 = Person.new( first-name => 'grace', last-name => 'hopper' ); say $p1.full-name(); # OUTPUT: «Grace Hopper»
Alternatively, the named parameters can be specified using the colon-pair syntax in Perl 6:
my $p0 = Person.new( :first-name<Sam>, :last-name<Ashe>, :age(42) ); my $p1 = Person.new( :first-name<Grace>, :last-name<Hopper> );
And should you have set up variables with names identical to the named parameters, you can use a shortcut that will use the name of the variable for the named parameter:
my $first-name = "Sam"; my $last-name = "Ashe"; my $age = 42; my $p0 = Person.new( :$first-name, :$last-name, :$age );
Ruby
In Ruby, constructors are created by defining a method called initialize
. This method is executed to initialize each new instance.
irb(main):001:0> class ExampleClass irb(main):002:1> def initialize irb(main):003:2> puts "Hello there" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> ExampleClass.new Hello there => #<ExampleClass:0x007fb3f4299118>
Visual Basic .NET
In Visual Basic .NET, constructors use a method declaration with the name "New
".
Class Foobar Private strData As String ' Constructor Public Sub New(ByVal someParam As String) strData = someParam End Sub End Class
' code somewhere else ' instantiating an object with the above constructor Dim foo As New Foobar(".NET")
See also
- Resource acquisition is initialization (RAII)
- Allocation site
- Creational pattern
- Destructor (computer programming)
- Global constructor in C++, and its C counterpart, ((constructor)) function attribute
Notes
- Eiffel routines are either procedures or functions. Procedures never have a return type. Functions always have a return type.
- Because the inherited class invariant must be satisfied, there is no mandatory call to the parents' constructors.
- The Eiffel standard requires fields to be initialized on first access, so it is not necessary to perform default field initialization during object creation.
References
- ^ Constructors and Destructors, from PHP online documentation
- Data model, from Python online documentation
- https://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order Constructor
- ^ Albahari, Joseph. C# 10 in a Nutshell. O'Reilly. ISBN 978-1-098-12195-2.
- "Fabulous Adventures in Coding". Eric Lippert. 2013-02-06. Retrieved 2014-04-05.
- Expert .NET 2.0 IL Assembler. APress. 2006-01-01. ISBN 9781430202233. Retrieved 2014-04-05.
- Static Constructor in C# on MSDN
- Skeet, Jon. C# in Depth. Manning. ISBN 978-1617294532.
- CFComponent
- Eiffel ISO/ECMA specification document
- Details on Constructor in java
- "Providing Constructors for Your Classes". Oracle Corporation. 2013. Retrieved 2013-12-20.
- OCaml manual
- Data model
- Data model