Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
m Small WP:COPYEDITs WP:EoS: clarify, WP:TERSE. MOS:FIRSTABBReviation clarify, define before WP:ABBR in parentheses. WP:LINKs: update-standardizes, needless WP:PIPEs > WP:NOPIPEs.
m Cut needless carriage return whitespace characters in sections: to standardize, aid work via small screens. WP:LINKs: add, update-standardize, underscores > spaces, needless WP:PIPEs > WP:NOPIPEs. MOS:FIRSTABBReviation clarify, define before WP:ABBR in parentheses.
Line 9:
 
== Types ==
 
=== Parameterized constructors ===
 
Constructors that can take at least one argument are termed as parameterized constructors. When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly. The method of calling the constructor implicitly is also called the shorthand method.
 
Line 53 ⟶ 51:
{{see also|Copy constructor (C++)}}
Like C++, Java also supports "Copy Constructor". But, unlike C++, Java doesn't create a default copy constructor if you don't write your own. Copy constructors define the actions performed by the compiler when copying class objects. A Copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object). It is used to create a copy of an existing object of the same class. Even though both classes are the same, it counts as a conversion constructor.
While copy constructors are usually abbreviated copy ctor or cctor, they have nothing to do with class constructors used in [[.NET]] using the same abbreviation.
 
=== Conversion constructors ===
 
Conversion constructors provide a means for a compiler to implicitly create an object belonging to one class based on an object of a different type. These constructors are usually invoked implicitly to convert arguments or operands to an appropriate type, but they may also be called explicitly.
 
=== Move constructors ===
 
In C++, [[move constructor (C++)|move constructors]] take an Rvalue reference to an object of the class, and are used to implement ownership transfer of the parameter object's resources.
 
== Syntax ==
 
* [[Java (programming language)|Java]], [[C++]], [[C Sharp (programming language)|C#]], [[ActionScript]], {{nowrap|[[PHP]] 4}} and [[MATLAB]] have a naming convention in which constructors have the same name as the class with which they are associated.
* 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>
Line 76 ⟶ 71:
 
== Memory organization ==
 
In Java, C#, and VB .NET, the constructor creates reference type objects in a special memory structure called the
"[[heap (data structure)|heap]]". Value types (such as int, double, etc.) are created in a sequential structure called the "[[stack (abstract data type)|stack]]".
Line 87 ⟶ 81:
 
=== 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.
 
Line 123 ⟶ 116:
 
=== C# ===
 
Example [[C Sharp (programming language)|C#]] constructor:
 
Line 153 ⟶ 145:
 
==== C# static constructor ====
 
In [[C Sharp (programming language)|C#]], a ''static constructor'' is a static data initializer.<ref name=Albahari>{{cite book |last=Albahari |first=Joseph |title= C# 10 in a Nutshell |publisher= O'Reilly |isbn= 978-1-098-12195-2}}</ref>{{rp|111-112}} Static constructors are also called ''class constructors''. Since the actual method generated has the name ''.cctor'' they are often also called "cctors".<ref>{{cite web|url=http://ericlippert.com/2013/02/06/static-constructors-part-one/ |title=Fabulous Adventures in Coding |publisher=Eric Lippert |date=2013-02-06|access-date=2014-04-05}}</ref><ref>{{cite book|url=https://books.google.com/books?id=oAcCRKd6EZgC&pg=PA222 |title=Expert .NET 2.0 IL Assembler |publisher=APress |date=2006-01-01|isbn=9781430202233 |access-date=2014-04-05}}</ref>
 
Line 188 ⟶ 179:
 
=== ColdFusion Markup Language (CFML) ===
 
[[ColdFusion Markup Language]] (CFML) uses a method named '<code>init</code>' as a constructor method.
 
Line 226 ⟶ 216:
 
=== Eiffel ===
 
In [[Eiffel (programming language)|Eiffel]], the routines which initialize new objects are called ''creation procedures''. Creation procedures have the following traits:
 
Line 287 ⟶ 276:
 
=== 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.
 
Line 321 ⟶ 309:
 
=== Java ===
 
In [[Java (programming language)|Java]], constructors differ from other methods in that:
 
Line 387 ⟶ 374:
 
=== JavaScript ===
 
As of ES6, [[JavaScript]] has direct constructors like many other programming languages. They are written as such
 
Line 415 ⟶ 401:
 
=== Object Pascal ===
 
In [[Object Pascal]], the constructor is similar to a [[factory method]]. The only syntactic difference to regular methods is the keyword <code>constructor</code> in front of the name (instead of <code>procedure</code> or <code>function</code>). It can have any name, though the convention is to have <code>Create</code> as prefix, such as in <code>CreateWithFormatting</code>. Creating an instance of a class works like calling a static method of a class: <code>TPerson.Create('Peter')</code>.
 
Line 443 ⟶ 428:
 
=== OCaml ===
 
In [[OCaml]], there is one constructor. Parameters are defined right after the class name. They can be used to initialize instance variables and are accessible throughout the class. An anonymous hidden method called <code>initializer</code> allows to evaluate an expression immediately after the object has been built.
<ref>[http://caml.inria.fr/pub/docs/manual-ocaml/index.html OCaml manual]</ref>
Line 464 ⟶ 448:
 
=== 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"/>
 
Line 487 ⟶ 470:
 
=== Perl 5 ===
 
In [[Perl]] version 5, by default, constructors are [[factory method]]s, that is, methods that create and return the object, concretely meaning create and return a blessed reference. A typical object is a reference to a hash, though rarely references to other types are used too. By convention the only constructor is named ''new'', though it is allowed to name it otherwise, or to have multiple constructors. For example, a Person class may have a constructor named ''new'', and a constructor ''new_from_file'' which reads a file for Person attributes, and ''new_from_person'' which uses another Person object as a template.
 
Line 522 ⟶ 504:
 
==== Perl 5 with Moose ====
 
In the [[Moose perl|Moose object system]] for Perl, most of this boilerplate can be omitted, a default ''new'' is created, attributes can be specified, and whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a ''BUILD'' method which the Moose generated constructor will call, after it has checked the arguments. A ''BUILDARGS'' method can be specified to handle constructor arguments not in hashref / key => value form.
 
Line 556 ⟶ 537:
 
=== 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>
 
Line 581 ⟶ 561:
 
=== Raku ===
 
In [[Raku (programming language)|Raku]], even more boilerplate can be omitted, given that a default ''new'' method is inherited, attributes can be specified, and whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a ''BUILD'' method which will get called to allow for custom initialization. A ''TWEAK'' method can be specified to post-process any attributes already (implicitly) initialized.
 
Line 634 ⟶ 613:
 
=== Ruby ===
 
In [[Ruby (programming language)|Ruby]], constructors are created by defining a method called <code>initialize</code>. This method is executed to initialize each new instance.
<syntaxhighlight lang="rbcon">
Line 649 ⟶ 627:
 
=== Visual Basic .NET ===
 
In [[Visual Basic .NET]], constructors use a method declaration with the name "<code>New</code>".
 
Line 670 ⟶ 647:
 
== See also ==
* [[Resource acquisition is initialization]] (RAII)
* [[Resource_acquisition_is_initialization|RAII]]
* [[Allocation site]]
* [[Creational pattern]]
* [[Destructor (computer scienceprogramming)|Destructor]]
* [[Global constructor]] in C++, and its C counterpart, [[((constructor))]] function attribute