This page allows you to examine the variables generated by the Edit Filter for an individual change.

Variables generated for this change

VariableValue
Whether or not the edit is marked as minor (no longer in use) (minor_edit)
false
Name of the user account (user_name)
'115.249.172.101'
Whether or not a user is editing through the mobile interface (user_mobile)
false
Page ID (page_id)
939453
Page namespace (page_namespace)
0
Page title without namespace (page_title)
'Constructor (object-oriented programming)'
Full page title (page_prefixedtitle)
'Constructor (object-oriented programming)'
Action (action)
'edit'
Edit summary/reason (summary)
'/* Defined constructors */ '
Old content model (old_content_model)
'wikitext'
New content model (new_content_model)
'wikitext'
Old page wikitext, before the edit (old_wikitext)
'{{refimprove|date=August 2010}} {{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 [[argument]]s that the constructor uses to set required [[member variable]]s. A constructor resembles an [[method (computer science)|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 == {{unreferenced section|date=June 2013}} === Defined constructors === Constructors that can take at least one argument are termed as parameterized constructors. For example: <source lang="cpp"> class Example { int x, y; public: Example(); Example(int a, int b); // Parameterized constructor }; Example :: Example() { } Example :: Example(int a, int b) { x = a; y = b; } </source> 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. <source lang="cpp"> Example e = Example(0, 50); // Explicit call Example e(0, 50); // Implicit call </source> === Default constructors === If the programmer does not supply a constructor for an instantiable class, most languages will provide a ''[[default constructor]]''. The behavior of the default constructor is language dependent. It may initialize data members to zero or other same values, or it may do nothing at all. Some languages (Java, C#, VB .NET) will default construct arrays of class types to contain [[null reference]]s. Languages without null references may not allow default construction of arrays of non default constructible objects, or require explicit initialization at the time of the creation (C++): <source lang="cpp"> #include <iostream> class student{ public: int a,b; student(a=0,b=0) //default constructor }; int main() { } </source> === Copy constructors === {{see also|Copy constructor (C++)}} '''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++, [[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]], and {{nowrap|[[PHP]] 4}} 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">[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. * In [[Visual Basic .NET]], the constructor is called "<code>New</code>". * In [[Python (programming language)|Python]], the constructor is split over two methods, "<code>__new__</code>" and "<code>__init__</code>". The <code>__new__</code> method is responsible for allocating memory for the instance, and receives the class as an argument (conventionally called "<code>cls</code>"). The <code>__init__</code> method (often called "the initialiser") is passed the newly created instance as an argument (conventionally called "<code>self</code>").<ref>[https://docs.python.org/3/reference/datamodel.html#basic-customization Data model], from Python online documentation</ref> * [[Object Pascal]] constructors are signified by the keyword "<code>constructor</code>" and can have user-defined names (but are mostly called "<code>Create</code>"). * In [[Objective-C]], the constructor method is split across two methods, "<code>alloc</code>" and "<code>init</code>" with the <code>alloc</code> method setting aside (allocating) memory for an instance of the class, and the <code>init</code> method handling the bulk of initializing the instance. A call to the method "<code>new</code>" invokes both the <code>alloc</code> and the <code>init</code> methods, for the class instance. == Memory organization == In Java, C# and VB .NET the constructor creates objects in a special memory structure called [[heap (data structure)|heap]] for reference types. Value types (such as int, double etc.), are created in a sequential structure called [[stack (abstract data type)|stack]]. VB .NET and C# allow use of ''new'' to create objects of value types. However, in those languages even use of new for value types creates objects only on stack. In C++, when constructor is invoked without new the objects are created on stack. When objects are created using new they are created on heap. They must be deleted implicitly by a destructor or explicitly by a call to operator ''delete''. == Language details == {{Split|Comparison of programming languages (OOP, constructors)|date=May 2016}} <!-- see also Category:Programming language comparisons --> === 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 cannot be ''synchronized'', ''final'', ''abstract'', ''native'', or ''static''. 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>[https://ranjeetkumarmaurya.wordpress.com/2017/02/06/constructor-in-java/ Details on Constructor in java]</ref> <source 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(); } </source> Java provides access to the [[superclass (computer science)|superclass's]] constructor through the <code>super</code> keyword. <source 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; } </source> <source lang="java"> // Code somewhere else // Instantiating an object with the above constructor Example e = new Example(42); </source> 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 <source lang="javascript"> class FooBar { constructor(baz) { this.baz = baz } } </source> This can be instantiated as such <source lang="javascript"> const foo = new FooBar('7') </source> The equivalent of this before ES6, was creating a function that instantiates an object as such <source lang="javascript"> var FooBar = function(baz) { this.baz = baz; } </source> 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>". <source lang="vbnet"> Class Foobar Private strData As String ' Constructor Public Sub New(ByVal someParam As String) strData = someParam End Sub End Class </source> <source lang="vbnet"> ' code somewhere else ' instantiating an object with the above constructor Dim foo As New Foobar(".NET") </source> === C# === Example [[C Sharp (programming language)|C#]] constructor: <source lang="csharp"> 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; } } </source> <source lang="csharp"> // Code somewhere // Instantiating an object with the constructor above MyClass c = new MyClass(42, "string"); </source> ==== C# static constructor ==== 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. Static variables are instantiated as well. <source lang="csharp"> public class MyClass { private static int _A; // Normal constructor static MyClass() { _A = 32; } // Standard default constructor public MyClass() { } } </source> <source lang="csharp"> // 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(); </source> === C++ === 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. 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. <source 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; }; </source> Example invocations: <source lang="cpp"> Foobar a, b(3), c(5, M_PI/4); </source> 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++ programming)|Rule of three]]. === F# === 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. <source lang="ocaml"> 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 </source> <source lang = "ocaml"> // 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 </source> === Eiffel === In [[Eiffel (programming language)|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'').{{Efn|Eiffel ''routines'' are either ''procedures'' or ''functions''. Procedures never have a return type. Functions always have a return type.}} * 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.{{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">[http://www.ecma-international.org/publications/standards/Ecma-367.htm 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.}} * Execute the creation procedure <code lang="eiffel">make</code> to the newly created instance. * Attach the newly initialized object to the entity <code lang="eiffel">x</code>. In the first snippet below, class <code lang="eiffel">POINT</code> is defined. The procedure <code lang="eiffel">make</code> is coded after the keyword <code lang="eiffel">feature</code>. The keyword <code lang="eiffel">create</code> introduces a list of procedures which can be used to initialize instances. In this case the list includes <code lang="eiffel">default_create</code>, a procedure with an empty implementation inherited from class <code lang="eiffel">ANY</code>, and the <code lang="eiffel">make</code> procedure coded within the class. <source lang="eiffel"> 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 ... </source> In the second snippet, a class which is a client to <code lang="eiffel">POINT</code> has a declarations <code lang="eiffel">my_point_1</code> and <code lang="eiffel">my_point_2</code> of type <code lang="eiffel">POINT</code>. In procedural code, <code lang="eiffel">my_point_1</code> is created as the origin (0.0, 0.0). Because no creation procedure is specified, the procedure <code lang="eiffel">default_create</code> inherited from class <code lang="eiffel">ANY</code> is used. This line could have been coded <code lang="eiffel">create my_point_1.default_create</code> . Only procedures named as creation procedures can be used in an instruction with the <code lang="eiffel">create</code> keyword. Next is a creation instruction for <code lang="eiffel">my_point_2</code>, providing initial values for the <code lang="eiffel">my_point_2</code>'s coordinates. The third instruction makes an ordinary instance call to the <code lang="eiffel">make</code> procedure to reinitialize the instance attached to <code lang="eiffel">my_point_2</code> with different values. <source lang="eiffel"> 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) ... </source> === CFML === [[CFML]] uses a method named '<code>init</code>' as a constructor method. '''Cheese.cfc''' <source lang="javascript"> component { // properties property name="cheeseName"; // constructor function Cheese init( required string cheeseName ) { variables.cheeseName = arguments.cheeseName; return this; } } </source> Create instance of a cheese. <source lang="javascript"> myCheese = new Cheese( 'Cheddar' ); </source> 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: <source lang="javascript"> component initmethod="Cheese" { // properties property name="cheeseName"; // constructor function Cheese Cheese( required string cheeseName ) { variables.cheeseName = arguments.cheeseName; return this; } } </source> === 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>. <source lang="delphi"> 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. </source> === Perl === 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. <source lang="perl"> 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; </source> === Perl with Moose === 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. <source lang="perl"> 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; </source> In both cases the Person class is instiated like this: <source lang="perl"> use Person; my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 ); </source> === 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"/> <source lang="php"> class Person { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } </source> === 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.) <source 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 </source> 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. <source lang="rbcon"> 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> </source> == See also == * [[Allocation site]] * [[Creational pattern]] * [[Destructor (computer science)|Destructor]] * [[Global constructor]] in C++, and its C counterpart, [[((constructor))]] function attribute == Notes == {{Notelist}} == References == {{Reflist|30em}} [[Category:Method (computer programming)]] [[Category:Programming language comparisons]]'
New page wikitext, after the edit (new_wikitext)
'{{refimprove|date=August 2010}} {{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 [[argument]]s that the constructor uses to set required [[member variable]]s. A constructor resembles an [[method (computer science)|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 == {{unreferenced section|date=June 2013}} === Defined constructors === Constructors that can take at least one argument are termed as parameterized constructors. For example: <source lang="cppcfgfxdgfh"> class Example { int x, y; public: Example(); Example(int a, int b); // Parameterized constructor }; Example :: Example() { } Example :: Example(int a, int b) { x = a; y = b; } </source> 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. <source lang="cpp"> Example e = Example(0, 50); // Explicit call Example e(0, 50); // Implicit call </source> === Default constructors === If the programmer does not supply a constructor for an instantiable class, most languages will provide a ''[[default constructor]]''. The behavior of the default constructor is language dependent. It may initialize data members to zero or other same values, or it may do nothing at all. Some languages (Java, C#, VB .NET) will default construct arrays of class types to contain [[null reference]]s. Languages without null references may not allow default construction of arrays of non default constructible objects, or require explicit initialization at the time of the creation (C++): <source lang="cpp"> #include <iostream> class student{ public: int a,b; student(a=0,b=0) //default constructor }; int main() { } </source> === Copy constructors === {{see also|Copy constructor (C++)}} '''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++, [[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]], and {{nowrap|[[PHP]] 4}} 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">[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. * In [[Visual Basic .NET]], the constructor is called "<code>New</code>". * In [[Python (programming language)|Python]], the constructor is split over two methods, "<code>__new__</code>" and "<code>__init__</code>". The <code>__new__</code> method is responsible for allocating memory for the instance, and receives the class as an argument (conventionally called "<code>cls</code>"). The <code>__init__</code> method (often called "the initialiser") is passed the newly created instance as an argument (conventionally called "<code>self</code>").<ref>[https://docs.python.org/3/reference/datamodel.html#basic-customization Data model], from Python online documentation</ref> * [[Object Pascal]] constructors are signified by the keyword "<code>constructor</code>" and can have user-defined names (but are mostly called "<code>Create</code>"). * In [[Objective-C]], the constructor method is split across two methods, "<code>alloc</code>" and "<code>init</code>" with the <code>alloc</code> method setting aside (allocating) memory for an instance of the class, and the <code>init</code> method handling the bulk of initializing the instance. A call to the method "<code>new</code>" invokes both the <code>alloc</code> and the <code>init</code> methods, for the class instance. == Memory organization == In Java, C# and VB .NET the constructor creates objects in a special memory structure called [[heap (data structure)|heap]] for reference types. Value types (such as int, double etc.), are created in a sequential structure called [[stack (abstract data type)|stack]]. VB .NET and C# allow use of ''new'' to create objects of value types. However, in those languages even use of new for value types creates objects only on stack. In C++, when constructor is invoked without new the objects are created on stack. When objects are created using new they are created on heap. They must be deleted implicitly by a destructor or explicitly by a call to operator ''delete''. == Language details == {{Split|Comparison of programming languages (OOP, constructors)|date=May 2016}} <!-- see also Category:Programming language comparisons --> === 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 cannot be ''synchronized'', ''final'', ''abstract'', ''native'', or ''static''. 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>[https://ranjeetkumarmaurya.wordpress.com/2017/02/06/constructor-in-java/ Details on Constructor in java]</ref> <source 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(); } </source> Java provides access to the [[superclass (computer science)|superclass's]] constructor through the <code>super</code> keyword. <source 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; } </source> <source lang="java"> // Code somewhere else // Instantiating an object with the above constructor Example e = new Example(42); </source> 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 <source lang="javascript"> class FooBar { constructor(baz) { this.baz = baz } } </source> This can be instantiated as such <source lang="javascript"> const foo = new FooBar('7') </source> The equivalent of this before ES6, was creating a function that instantiates an object as such <source lang="javascript"> var FooBar = function(baz) { this.baz = baz; } </source> 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>". <source lang="vbnet"> Class Foobar Private strData As String ' Constructor Public Sub New(ByVal someParam As String) strData = someParam End Sub End Class </source> <source lang="vbnet"> ' code somewhere else ' instantiating an object with the above constructor Dim foo As New Foobar(".NET") </source> === C# === Example [[C Sharp (programming language)|C#]] constructor: <source lang="csharp"> 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; } } </source> <source lang="csharp"> // Code somewhere // Instantiating an object with the constructor above MyClass c = new MyClass(42, "string"); </source> ==== C# static constructor ==== 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. Static variables are instantiated as well. <source lang="csharp"> public class MyClass { private static int _A; // Normal constructor static MyClass() { _A = 32; } // Standard default constructor public MyClass() { } } </source> <source lang="csharp"> // 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(); </source> === C++ === 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. 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. <source 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; }; </source> Example invocations: <source lang="cpp"> Foobar a, b(3), c(5, M_PI/4); </source> 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++ programming)|Rule of three]]. === F# === 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. <source lang="ocaml"> 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 </source> <source lang = "ocaml"> // 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 </source> === Eiffel === In [[Eiffel (programming language)|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'').{{Efn|Eiffel ''routines'' are either ''procedures'' or ''functions''. Procedures never have a return type. Functions always have a return type.}} * 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.{{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">[http://www.ecma-international.org/publications/standards/Ecma-367.htm 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.}} * Execute the creation procedure <code lang="eiffel">make</code> to the newly created instance. * Attach the newly initialized object to the entity <code lang="eiffel">x</code>. In the first snippet below, class <code lang="eiffel">POINT</code> is defined. The procedure <code lang="eiffel">make</code> is coded after the keyword <code lang="eiffel">feature</code>. The keyword <code lang="eiffel">create</code> introduces a list of procedures which can be used to initialize instances. In this case the list includes <code lang="eiffel">default_create</code>, a procedure with an empty implementation inherited from class <code lang="eiffel">ANY</code>, and the <code lang="eiffel">make</code> procedure coded within the class. <source lang="eiffel"> 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 ... </source> In the second snippet, a class which is a client to <code lang="eiffel">POINT</code> has a declarations <code lang="eiffel">my_point_1</code> and <code lang="eiffel">my_point_2</code> of type <code lang="eiffel">POINT</code>. In procedural code, <code lang="eiffel">my_point_1</code> is created as the origin (0.0, 0.0). Because no creation procedure is specified, the procedure <code lang="eiffel">default_create</code> inherited from class <code lang="eiffel">ANY</code> is used. This line could have been coded <code lang="eiffel">create my_point_1.default_create</code> . Only procedures named as creation procedures can be used in an instruction with the <code lang="eiffel">create</code> keyword. Next is a creation instruction for <code lang="eiffel">my_point_2</code>, providing initial values for the <code lang="eiffel">my_point_2</code>'s coordinates. The third instruction makes an ordinary instance call to the <code lang="eiffel">make</code> procedure to reinitialize the instance attached to <code lang="eiffel">my_point_2</code> with different values. <source lang="eiffel"> 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) ... </source> === CFML === [[CFML]] uses a method named '<code>init</code>' as a constructor method. '''Cheese.cfc''' <source lang="javascript"> component { // properties property name="cheeseName"; // constructor function Cheese init( required string cheeseName ) { variables.cheeseName = arguments.cheeseName; return this; } } </source> Create instance of a cheese. <source lang="javascript"> myCheese = new Cheese( 'Cheddar' ); </source> 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: <source lang="javascript"> component initmethod="Cheese" { // properties property name="cheeseName"; // constructor function Cheese Cheese( required string cheeseName ) { variables.cheeseName = arguments.cheeseName; return this; } } </source> === 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>. <source lang="delphi"> 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. </source> === Perl === 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. <source lang="perl"> 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; </source> === Perl with Moose === 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. <source lang="perl"> 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; </source> In both cases the Person class is instiated like this: <source lang="perl"> use Person; my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 ); </source> === 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"/> <source lang="php"> class Person { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } </source> === 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.) <source 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 </source> 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. <source lang="rbcon"> 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> </source> == See also == * [[Allocation site]] * [[Creational pattern]] * [[Destructor (computer science)|Destructor]] * [[Global constructor]] in C++, and its C counterpart, [[((constructor))]] function attribute == Notes == {{Notelist}} == References == {{Reflist|30em}} [[Category:Method (computer programming)]] [[Category:Programming language comparisons]]'
Whether or not the change was made through a Tor exit node (tor_exit_node)
0
Unix timestamp of change (timestamp)
1514886792