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

Variables generated for this change

VariableValue
Name of the user account (user_name)
'41.216.209.228'
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)
'/* Copy constructors */ '
Whether or not the edit is marked as minor (no longer in use) (minor_edit)
false
Old page wikitext, before the edit (old_wikitext)
'{{Multiple issues | copy edit = February 2012 | essay-like = February 2012 | refimprove = August 2010 }} {{ProgLangCompare}} Definition: "a constructor is an initialization routine having the same name as the class name, which is called automatically at the time of object creation." In [[object-oriented programming]], a '''constructor''' (sometimes shortened to '''ctor''') in a [[class (computer science)|class]] is a special type of [[subroutine]] called at the [[object lifetime#Creating objects|creation of an object]]. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created. It is called a constructor because it constructs the values of data members of the class. A constructor resembles an [[method (computer science)|instance method]], but it differs from a method in that it never has an explicit return-type, it is not inherited (though many languages provide access to the [[superclass (computer science)|superclass's]] constructor, for example through the <code>super</code> keyword in [[Java (programming language)|Java]]), and it usually has different rules for scope modifiers. Constructors are often distinguished by having 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 [[invariant (computer science)|invariant]] of the class, failing if the invariant is invalid. A properly written constructor will leave the [[object (computer science)|object]] in a ''valid'' state. [[Immutable object]]s must be initialized in a constructor. Programmers can also use the term ''constructor'' to denote one of the tags that wraps data in an [[algebraic data type]]. This is a different usage than in this article.{{Dubious|date=August 2009}} Most languages allow [[method overloading|overloading]] the constructor in that there can be more than one constructor for a class, each having different parameters. Some languages take consideration of some special types of constructors. == Types of constructors == === Parameterized constructors === Constructors that can take arguments are termed as parameterized constructors. The number of arguments can be greater or equal to one(1). For example: <source lang="c"> class example { int p, q; public: example(int a, int b); //parameterized constructor }; example :: example(int a, int b) { p = a; q = 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="c"> 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, a typical compiler 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. === Copy constructors === [[Copy constructor]]s 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. A constructor is a special type of method. === 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. == 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 of which they are associated with. * 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 called "<code>__init__</code>" and is always passed its parent class as an argument, the name for which is generally defined as "<code>self</code>". <!-- * In [[R --> <!-- I'm not sure what that's about, but I think someone tried to add Ruby, but stopped half-way. --> * [[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. == Java == In [[Java (programming language)|Java]], some of the differences between other methods and constructors are: * Constructors never have an explicit return type. * Constructors cannot be directly invoked (the keyword “<code>new</code>” must be used). * Constructors cannot be synchronized, final, abstract, native, or static. '''Apart from this, a Java constructor performs the following functions in the following order:''' # It initializes the class variables to default values. (Byte, short, int, long, float, and double variables default to their respective zero values, booleans to false, chars to the null character ('\u0000') and references of any objects to null.) # It then calls the super class constructor (default constructor of super class only if no constructor is defined). # It then initializes the class variables to the specified values like ex: int var = 10; or float var = 10.0f and so on. # It then executes the body of the constructor. In Java, C#, and VB .NET for reference types the constructor creates objects in a special part of memory called heap. On the other hand the value types (such as int, double etc.), are created in a sequential memory called 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. On the other hand when objects are created using new they are created on heap which must be deleted implicitly by a destructor or explicitly by a call to operator delete. Most languages provides a default constructor if programmer provides no constructor. However, this language provided constructor is taken away as soon as programmer provides any constructor in the class code. In C++ a default constructor is REQUIRED if an array of class objects is to be created. Other languages (Java, C#, VB .NET) have no such restriction. In C++ copy constructor is called implicitly when class objects are returned from a method by return mechanism or when class objects are passed by value to a function. C++ provides a copy constructor if programmer provides no constructor at all. That is taken away as soon as any constructor is provided by the programmer. C++ provided copy constructor ONLY makes member-wise copy or shallow copies. For deep copies a programmer written copy constructor that makes deep copies will be required. Generally a rule of three is observed. For a class that should have a copy constructor to make deep copies, the three below must be provided. 1. Copy constructor 2. Overloading of assignment operator. 3. A destructor. The above is called rule of three in C++. If cloning of objects is not desired in C++ then copy constructor must be declared private. <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> == 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# == In [[C Sharp (programming language)|C#]], a constructor is this. <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 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 can be called once and call is made implicitly by the run-time right before the first time the class is accessed. Any call to a class (static or constructor call), triggers the static constructor execution. Static constructors are thread safe and are a great way to implement a [[singleton pattern]]. When used in a [[generic programming]] class, static constructors are called on 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 does not return anything. It can have parameters, like any [[member function]]s (methods). Constructor functions should be declared in the public section. The constructor has two parts. First is the [[initializer list]] which comes after the [[parameter (computer science)|parameter list]] and before the opening curly bracket of the method's body. It starts with a colon and separated by commas. You are not always required to have initializer list, but it gives the opportunity to construct data members with parameters so you can save time (one construction instead of a construction and an assignment). Sometimes you must have initializer list for example if you have ''const'' or reference type data members, or members that cannot be default constructed (they don't have parameterless constructor). The order of the list should be the order of the declaration of the data members, because the execution order is that. The second part is the body which is a normal method body surrounded by curly brackets. C++ allows more than one constructor. The other constructors cannot be called, but can have default values for the parameters. The constructor of a [[base class]] (or base classes) can also be called by a derived class. Constructor functions cannot be inherited and their addresses cannot be referred. When memory allocation is required, the operators new and delete 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 implemented by hand the compiler gives a default implementation which 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 } // Other member functions private: double x; // Data members, they should be private double y; }; </source> Example invocations: <source lang="cpp"> Foobar a, b(3), c(5, M_PI/4); </source> You can write a private data member function at the top section before writing public specifier. If you no longer have access to a constructor then you can use the destructor. === Failure === A constructor that cannot create a valid value should throw an [[Exception handling|exception]]. This is because exceptions should be thrown when [[Postcondition|post-conditions]] cannot be met, and the post-condition of a constructor is the existence of a valid object. An object which throws during its constructor never comes into existence (although some of its member objects might). This affects how one handles errors and special consideration must be given for exceptions emitted by member variables' constructors [http://www.gotw.ca/gotw/066.htm]. == 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'''. They are similar to constructors in some ways and different in others. Creation procedures have the following traits: * Creation procedures never have an explicit return type (by definition of '''procedure''').<ref>Eiffel '''routines''' are either '''procedures''' or '''functions'''. Procedures never have a return type. Functions always have a return type.</ref> * Creation procedures are named. Names are restricted only to valid identifiers. * Creation procedures are designated by name as creation procedures in the text of the class. * Creation procedures can be directly 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.<ref>Because the inherited class invariant must be satisfied, there is no mandatory call to the parents' constructors.</ref> 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>.<ref>The Eiffel standard requires fields to be initialized on first access, so it is not necessary to perform default field initialization during object creation.</ref> *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> == ColdFusion == [[ColdFusion]] has no constructor method. Developers using it commonly create an '<code>init</code>' method that acts as a pseudo-constructor. <source lang="cfm"> <cfcomponent displayname="Cheese"> <!--- properties ---> <cfset variables.cheeseName = "" /> <!--- pseudo-constructor ---> <cffunction name="init" returntype="Cheese"> <cfargument name="cheeseName" type="string" required="true" /> <cfset variables.cheeseName = arguments.cheeseName /> <cfreturn this /> </cffunction> </cfcomponent> </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="Pascal"> program OopProgram; interface type TPerson = class private FName: string; public property Name: string read FName; constructor Create(AName: string); end; implementation 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]] version 5, by default, constructors must provide code to create the object (a reference, usually a hash reference, but sometimes an array reference, scalar reference or code reference) and bless it into the correct class. By convention the constructor is named ''new'', but it is not required, or required to be the only one. 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; use strict; use warnings; # constructor sub new { # class name is passed in as 0th # argument my $class = shift; # check if the arguments to the # constructor are key => value pairs die "$class needs arguments as key => value pairs" unless (@_ % 2 == 0); # default arguments my %defaults; # create object as combination of default # values and arguments passed my $obj = { %defaults, @_, }; # check for required arguments die "Need first_name and last_name for Person" unless ($obj->{first_name} and $obj->{last_name}); # any custom checks of data if ($obj->{age} && $obj->{age} < 18)) { # no under-18s die "No under-18 Persons"; } # return object blessed into Person class bless $obj, $class; } 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>, which the keyword <code>new</code> automatically calls after creating the object. It is usually used to automatically perform various 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 the function parameters in between the parentheses.<ref name="php5cpnstructor"/> <source lang="php"> class Person { private $name; function __construct($name) { $this->name = $name; } function getName() { return $this->name; } } </source> However, constructor in PHP version 4 (and earlier) is a method in a class with the same name of the class. In PHP 5 for reasons of backwards compatibility with PHP 4, when method called <code>__construct</code> is not found, a method with the same name as the class will be called instead. Since PHP 5.3.3 this fallback mechanism will only work for non-namespaced classes.<ref name="php5cpnstructor"/> <source lang="php"> class Person { private $name; function Person($name) { $this->name = $name; } function getName() { return $this->name; } } </source> == Python == In [[Python (programming language)|Python]], constructors are created by defining an __new__ method, and are called when a new instance is created by calling the class. Unlike other languages such as C++, derived classes in Python do not call their base classes' constructors. However, when a constructor is not defined, the next one found in the class's [[C3 linearization|Method Resolution Order]] will be called. Due to Python's use of [[duck typing]], class members are often defined in the constructor, rather than in the class definition itself. In case of the initial values (not methods) are needed, the __init__ method can be defined. <source lang="python"> class ExampleClass(object): def __new__(self): # We override the constructor to return none instead. return None exampleInstance = ExampleClass() print exampleInstance None </source> == Ruby == In [[Ruby (programming language)|Ruby]], constructors are created by defining a method called <code>initialize</code>. This method is executed everytime a new instance is created. <source lang="ruby"> class ExampleClass def initialize return "Hello there" exampleInstance = ExampleClass.new puts exampleInstance # => "Hello there" </source> == Constructors simplified, with pseudocode == Constructors are always part of the implementation of classes. A class (in programming) refers to a specification of the general traits of the set of objects that are members of the class rather than the specific traits of any object at all. A simple analogy in [[pseudocode]] follows. Consider the set (or class, using its generic meaning) of students at some school. Thus we have <source lang="text"> class Student { // refers to the class of students // ... more omitted ... } </source> However, the class <code>Student</code> just provides a generic prototype of what a student should be. To use it, the programmer creates each student as an ''object'' or ''instance'' of the class. This object is a real quantity of data in memory whose size, layout, traits, and (to some extent) behavior are determined by the class definition. The usual way of creating objects is to call a constructor (classes may in general have many independent constructors). For example, <source lang="text"> class Student { Student (String studentName, String Address, int ID) { // ... storage of input data and other internal fields here ... } // ... } </source> == See also == * [[Destructor (computer science)]] == Notes == {{reflist}} == References == {{reflist}} [[Category:Method (computer programming)]] [[bg:Конструктор (обектно-ореинтирано програмиране)]] [[cs:Konstruktor]] [[de:Konstruktoren und Destruktoren]] [[es:Constructor (informática)]] [[fr:Constructeur (programmation)]] [[ko:생성자]] [[it:Costruttore]] [[he:בנאי (מדעי המחשב)]] [[lt:Konstruktorius]] [[nl:Constructor]] [[ja:コンストラクタ]] [[pt:Construtor]] [[ru:Конструктор (программирование)]] [[sv:Konstruktor]] [[ta:கட்டுநர் (பொருள் நோக்கு நிரலாக்கம்)]] [[uk:Конструктор (програмування)]]'
New page wikitext, after the edit (new_wikitext)
'{{Multiple issues | copy edit = February 2012 | essay-like = February 2012 | refimprove = August 2010 }} {{ProgLangCompare}} Definition: "a constructor is an initialization routine having the same name as the class name, which is called automatically at the time of object creation." In [[object-oriented programming]], a '''constructor''' (sometimes shortened to '''ctor''') in a [[class (computer science)|class]] is a special type of [[subroutine]] called at the [[object lifetime#Creating objects|creation of an object]]. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created. It is called a constructor because it constructs the values of data members of the class. A constructor resembles an [[method (computer science)|instance method]], but it differs from a method in that it never has an explicit return-type, it is not inherited (though many languages provide access to the [[superclass (computer science)|superclass's]] constructor, for example through the <code>super</code> keyword in [[Java (programming language)|Java]]), and it usually has different rules for scope modifiers. Constructors are often distinguished by having 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 [[invariant (computer science)|invariant]] of the class, failing if the invariant is invalid. A properly written constructor will leave the [[object (computer science)|object]] in a ''valid'' state. [[Immutable object]]s must be initialized in a constructor. Programmers can also use the term ''constructor'' to denote one of the tags that wraps data in an [[algebraic data type]]. This is a different usage than in this article.{{Dubious|date=August 2009}} Most languages allow [[method overloading|overloading]] the constructor in that there can be more than one constructor for a class, each having different parameters. Some languages take consideration of some special types of constructors. == Types of constructors == === Parameterized constructors === Constructors that can take arguments are termed as parameterized constructors. The number of arguments can be greater or equal to one(1). For example: <source lang="c"> class example { int p, q; public: example(int a, int b); //parameterized constructor }; example :: example(int a, int b) { p = a; q = 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="c"> 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, a typical compiler 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. === Copy constructors === [[Copy constructor]]s 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). Marete Polo dio bleksem fuck u bitch ass bitch. 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. A constructor is a special type of method. === 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. == 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 of which they are associated with. * 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 called "<code>__init__</code>" and is always passed its parent class as an argument, the name for which is generally defined as "<code>self</code>". <!-- * In [[R --> <!-- I'm not sure what that's about, but I think someone tried to add Ruby, but stopped half-way. --> * [[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. == Java == In [[Java (programming language)|Java]], some of the differences between other methods and constructors are: * Constructors never have an explicit return type. * Constructors cannot be directly invoked (the keyword “<code>new</code>” must be used). * Constructors cannot be synchronized, final, abstract, native, or static. '''Apart from this, a Java constructor performs the following functions in the following order:''' # It initializes the class variables to default values. (Byte, short, int, long, float, and double variables default to their respective zero values, booleans to false, chars to the null character ('\u0000') and references of any objects to null.) # It then calls the super class constructor (default constructor of super class only if no constructor is defined). # It then initializes the class variables to the specified values like ex: int var = 10; or float var = 10.0f and so on. # It then executes the body of the constructor. In Java, C#, and VB .NET for reference types the constructor creates objects in a special part of memory called heap. On the other hand the value types (such as int, double etc.), are created in a sequential memory called 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. On the other hand when objects are created using new they are created on heap which must be deleted implicitly by a destructor or explicitly by a call to operator delete. Most languages provides a default constructor if programmer provides no constructor. However, this language provided constructor is taken away as soon as programmer provides any constructor in the class code. In C++ a default constructor is REQUIRED if an array of class objects is to be created. Other languages (Java, C#, VB .NET) have no such restriction. In C++ copy constructor is called implicitly when class objects are returned from a method by return mechanism or when class objects are passed by value to a function. C++ provides a copy constructor if programmer provides no constructor at all. That is taken away as soon as any constructor is provided by the programmer. C++ provided copy constructor ONLY makes member-wise copy or shallow copies. For deep copies a programmer written copy constructor that makes deep copies will be required. Generally a rule of three is observed. For a class that should have a copy constructor to make deep copies, the three below must be provided. 1. Copy constructor 2. Overloading of assignment operator. 3. A destructor. The above is called rule of three in C++. If cloning of objects is not desired in C++ then copy constructor must be declared private. <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> == 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# == In [[C Sharp (programming language)|C#]], a constructor is this. <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 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 can be called once and call is made implicitly by the run-time right before the first time the class is accessed. Any call to a class (static or constructor call), triggers the static constructor execution. Static constructors are thread safe and are a great way to implement a [[singleton pattern]]. When used in a [[generic programming]] class, static constructors are called on 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 does not return anything. It can have parameters, like any [[member function]]s (methods). Constructor functions should be declared in the public section. The constructor has two parts. First is the [[initializer list]] which comes after the [[parameter (computer science)|parameter list]] and before the opening curly bracket of the method's body. It starts with a colon and separated by commas. You are not always required to have initializer list, but it gives the opportunity to construct data members with parameters so you can save time (one construction instead of a construction and an assignment). Sometimes you must have initializer list for example if you have ''const'' or reference type data members, or members that cannot be default constructed (they don't have parameterless constructor). The order of the list should be the order of the declaration of the data members, because the execution order is that. The second part is the body which is a normal method body surrounded by curly brackets. C++ allows more than one constructor. The other constructors cannot be called, but can have default values for the parameters. The constructor of a [[base class]] (or base classes) can also be called by a derived class. Constructor functions cannot be inherited and their addresses cannot be referred. When memory allocation is required, the operators new and delete 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 implemented by hand the compiler gives a default implementation which 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 } // Other member functions private: double x; // Data members, they should be private double y; }; </source> Example invocations: <source lang="cpp"> Foobar a, b(3), c(5, M_PI/4); </source> You can write a private data member function at the top section before writing public specifier. If you no longer have access to a constructor then you can use the destructor. === Failure === A constructor that cannot create a valid value should throw an [[Exception handling|exception]]. This is because exceptions should be thrown when [[Postcondition|post-conditions]] cannot be met, and the post-condition of a constructor is the existence of a valid object. An object which throws during its constructor never comes into existence (although some of its member objects might). This affects how one handles errors and special consideration must be given for exceptions emitted by member variables' constructors [http://www.gotw.ca/gotw/066.htm]. == 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'''. They are similar to constructors in some ways and different in others. Creation procedures have the following traits: * Creation procedures never have an explicit return type (by definition of '''procedure''').<ref>Eiffel '''routines''' are either '''procedures''' or '''functions'''. Procedures never have a return type. Functions always have a return type.</ref> * Creation procedures are named. Names are restricted only to valid identifiers. * Creation procedures are designated by name as creation procedures in the text of the class. * Creation procedures can be directly 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.<ref>Because the inherited class invariant must be satisfied, there is no mandatory call to the parents' constructors.</ref> 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>.<ref>The Eiffel standard requires fields to be initialized on first access, so it is not necessary to perform default field initialization during object creation.</ref> *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> == ColdFusion == [[ColdFusion]] has no constructor method. Developers using it commonly create an '<code>init</code>' method that acts as a pseudo-constructor. <source lang="cfm"> <cfcomponent displayname="Cheese"> <!--- properties ---> <cfset variables.cheeseName = "" /> <!--- pseudo-constructor ---> <cffunction name="init" returntype="Cheese"> <cfargument name="cheeseName" type="string" required="true" /> <cfset variables.cheeseName = arguments.cheeseName /> <cfreturn this /> </cffunction> </cfcomponent> </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="Pascal"> program OopProgram; interface type TPerson = class private FName: string; public property Name: string read FName; constructor Create(AName: string); end; implementation 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]] version 5, by default, constructors must provide code to create the object (a reference, usually a hash reference, but sometimes an array reference, scalar reference or code reference) and bless it into the correct class. By convention the constructor is named ''new'', but it is not required, or required to be the only one. 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; use strict; use warnings; # constructor sub new { # class name is passed in as 0th # argument my $class = shift; # check if the arguments to the # constructor are key => value pairs die "$class needs arguments as key => value pairs" unless (@_ % 2 == 0); # default arguments my %defaults; # create object as combination of default # values and arguments passed my $obj = { %defaults, @_, }; # check for required arguments die "Need first_name and last_name for Person" unless ($obj->{first_name} and $obj->{last_name}); # any custom checks of data if ($obj->{age} && $obj->{age} < 18)) { # no under-18s die "No under-18 Persons"; } # return object blessed into Person class bless $obj, $class; } 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>, which the keyword <code>new</code> automatically calls after creating the object. It is usually used to automatically perform various 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 the function parameters in between the parentheses.<ref name="php5cpnstructor"/> <source lang="php"> class Person { private $name; function __construct($name) { $this->name = $name; } function getName() { return $this->name; } } </source> However, constructor in PHP version 4 (and earlier) is a method in a class with the same name of the class. In PHP 5 for reasons of backwards compatibility with PHP 4, when method called <code>__construct</code> is not found, a method with the same name as the class will be called instead. Since PHP 5.3.3 this fallback mechanism will only work for non-namespaced classes.<ref name="php5cpnstructor"/> <source lang="php"> class Person { private $name; function Person($name) { $this->name = $name; } function getName() { return $this->name; } } </source> == Python == In [[Python (programming language)|Python]], constructors are created by defining an __new__ method, and are called when a new instance is created by calling the class. Unlike other languages such as C++, derived classes in Python do not call their base classes' constructors. However, when a constructor is not defined, the next one found in the class's [[C3 linearization|Method Resolution Order]] will be called. Due to Python's use of [[duck typing]], class members are often defined in the constructor, rather than in the class definition itself. In case of the initial values (not methods) are needed, the __init__ method can be defined. <source lang="python"> class ExampleClass(object): def __new__(self): # We override the constructor to return none instead. return None exampleInstance = ExampleClass() print exampleInstance None </source> == Ruby == In [[Ruby (programming language)|Ruby]], constructors are created by defining a method called <code>initialize</code>. This method is executed everytime a new instance is created. <source lang="ruby"> class ExampleClass def initialize return "Hello there" exampleInstance = ExampleClass.new puts exampleInstance # => "Hello there" </source> == Constructors simplified, with pseudocode == Constructors are always part of the implementation of classes. A class (in programming) refers to a specification of the general traits of the set of objects that are members of the class rather than the specific traits of any object at all. A simple analogy in [[pseudocode]] follows. Consider the set (or class, using its generic meaning) of students at some school. Thus we have <source lang="text"> class Student { // refers to the class of students // ... more omitted ... } </source> However, the class <code>Student</code> just provides a generic prototype of what a student should be. To use it, the programmer creates each student as an ''object'' or ''instance'' of the class. This object is a real quantity of data in memory whose size, layout, traits, and (to some extent) behavior are determined by the class definition. The usual way of creating objects is to call a constructor (classes may in general have many independent constructors). For example, <source lang="text"> class Student { Student (String studentName, String Address, int ID) { // ... storage of input data and other internal fields here ... } // ... } </source> == See also == * [[Destructor (computer science)]] == Notes == {{reflist}} == References == {{reflist}} [[Category:Method (computer programming)]] [[bg:Конструктор (обектно-ореинтирано програмиране)]] [[cs:Konstruktor]] [[de:Konstruktoren und Destruktoren]] [[es:Constructor (informática)]] [[fr:Constructeur (programmation)]] [[ko:생성자]] [[it:Costruttore]] [[he:בנאי (מדעי המחשב)]] [[lt:Konstruktorius]] [[nl:Constructor]] [[ja:コンストラクタ]] [[pt:Construtor]] [[ru:Конструктор (программирование)]] [[sv:Konstruktor]] [[ta:கட்டுநர் (பொருள் நோக்கு நிரலாக்கம்)]] [[uk:Конструктор (програмування)]]'
Whether or not the change was made through a Tor exit node (tor_exit_node)
0
Unix timestamp of change (timestamp)
1354085032