Content deleted Content added
m linking |
DarthKitty (talk | contribs) m →Language details: alphabetize |
||
Line 86:
{{Split|Comparison of programming languages (OOP, constructors)|date=May 2016}} <!-- see also Category:Programming language comparisons -->
===
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.
<syntaxhighlight lang="cpp">
class Foobar {
public:
Foobar(double r = 1.0,
double alpha = 0.0) // Constructor, parameters with default values.
: x_(r * cos(alpha)) // <- Initializer list
{
y_ = r * sin(alpha); // <- Normal assignment
}
private:
double x_;
double y_;
};
</syntaxhighlight>
Example invocations:
<syntaxhighlight lang="cpp">
Foobar a,
b(3),
c(5, M_PI/4);
</syntaxhighlight>
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]].
=== C# ===
Line 266 ⟶ 187:
</syntaxhighlight>
===
[[CFML]] uses a method named '<code>init</code>' as a constructor method.
'''Cheese.cfc'''
<syntaxhighlight lang="javascript">
component {
// properties
property name="cheeseName";
// constructor
function Cheese init( required string cheeseName ) {
variables.cheeseName = arguments.cheeseName;
return this;
}
}
</syntaxhighlight>
Create instance of a cheese.
<syntaxhighlight lang="javascript">
myCheese = new Cheese( 'Cheddar' );
</syntaxhighlight>
Since ColdFusion 10,<ref>[https://wikidocs.adobe.com/wiki/display/coldfusionen/cfcomponent CFComponent]</ref> CFML has also supported specifying the name of the constructor method:
<syntaxhighlight lang="javascript">
component initmethod="Cheese" {
// properties
property name="cheeseName";
// constructor
function Cheese Cheese( required string cheeseName ) {
variables.cheeseName = arguments.cheeseName;
return this;
}
}
</syntaxhighlight>
Line 397 ⟶ 286:
</syntaxhighlight>
===
In [[F Sharp (programming language)|F#]], a constructor can include any <code>let</code> or <code>do</code> statements defined in a class. <code>let</code> statements define private fields and <code>do</code> statements execute code. Additional constructors can be defined using the <code>new</code> keyword.
<syntaxhighlight lang="fsharp">
type MyClass(_a : int, _b : string) = class
// Primary constructor
let b = _b
do printfn "a = %i, b = %s" a b
// Additional constructors
new(_a : int) = MyClass(_a, "") then
printfn "Integer parameter given"
new(_b : string) = MyClass(0, _b) then
printfn "String parameter given"
new() = MyClass(0, "") then
printfn "No parameter given"
end
</syntaxhighlight>
<syntaxhighlight lang = "fsharp">
// Code somewhere
// instantiating an object with the primary constructor
let c1 = new MyClass(42, "string")
// instantiating an object with additional constructors
let c2 = new MyClass(42)
let c3 = new MyClass("string")
let c4 = MyClass() // "new" keyword is optional
</syntaxhighlight>
=== Java ===
In [[Java (programming language)|Java]], constructors differ from other methods in that:
* Constructors never have an explicit return type.
* Constructors cannot be directly invoked (the keyword “<code>new</code>” invokes them).
* Constructors should not have non-access modifiers.
Java constructors perform the following tasks in the following order:
# Call the default constructor of the superclass if no constructor is defined.
# Initialize member variables to the specified values.
# Executes the body of the constructor.
Java permit users to call one constructor in another constructor using <code>this()</code> keyword.
But <code>this()</code> must be first statement. <ref>[https://ranjeetkumarmaurya.wordpress.com/2017/02/06/constructor-in-java/ Details on Constructor in java]</ref>
<syntaxhighlight lang="java">
class Example
{
Example() // Non-parameterized constructor
{
this(1); // Calling of constructor
System.out.println("0-arg-cons");
}
Example(int a) // Parameterized constructor
{
System.out.println("1-arg-cons");
}
}
public static void main(String[] args)
{
Example e = new Example();
}
</syntaxhighlight>
Java provides access to the [[superclass (computer science)|superclass's]] constructor through the <code>super</code> keyword.
<syntaxhighlight lang="java">
public class Example
{
// Definition of the constructor.
public Example()
{
this(1);
}
// Overloading a constructor
public Example(int input)
{
data = input; // This is an assignment
}
// Declaration of instance variable(s).
private int data;
}
</syntaxhighlight>
<syntaxhighlight lang="java">
// Code somewhere else
// Instantiating an object with the above constructor
Example e = new Example(42);
</syntaxhighlight>
A constructor taking zero number of arguments is called a "no-arguments" or "no-arg" constructor.<ref>{{cite web|url=http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html|title= Providing Constructors for Your Classes |publisher=Oracle Corporation|date=2013|access-date=2013-12-20}}</ref>
=== JavaScript ===
As of ES6, [[JavaScript]] has direct constructors like many other programming languages. They are written as such
<syntaxhighlight lang="javascript">
class FooBar {
constructor(baz) {
this.baz = baz
}
}
</syntaxhighlight>
This can be instantiated as such
<syntaxhighlight lang="javascript">
const foo = new FooBar('7')
</syntaxhighlight>
The equivalent of this before ES6, was creating a function that instantiates an object as such
<syntaxhighlight lang="javascript">
function FooBar (baz) {
this.baz = baz;
}
</syntaxhighlight>
This is instantiated the same way as above.
=== Object Pascal ===
Line 461 ⟶ 440:
Person := TPerson.Create('Peter'); // allocates an instance of TPerson and then calls TPerson.Create with the parameter AName = 'Peter'
end.
</syntaxhighlight>
=== OCaml ===
In [[OCaml (programming language)|OCaml]], there is one constructor. Parameters are defined right after the class name. They can be used to initialize instance variables and are accessible throughout the class. An anonymous hidden method called <code>initializer</code> allows to evaluate an expression immediately after the object has been built.
<ref>[http://caml.inria.fr/pub/docs/manual-ocaml/index.html OCaml manual]</ref>
<syntaxhighlight lang="ocaml">
class person first_name last_name =
object
val full_name = first_name ^ " " ^ last_name
initializer
print_endline("Hello there, I am " ^ full_name ^ ".")
method get_last_name = last_name
end;;
let alonzo = new person "Alonzo" "Church" in (*Hello there, I am Alonzo Church.*)
print_endline alonzo#get_last_name (*Church*)
</syntaxhighlight>
=== PHP ===
In [[PHP]] version 5 and above, the constructor is a method named <code>__construct()</code> (notice that it's a double underscore), which the keyword <code>new</code> automatically calls after creating the object. It is usually used to automatically perform initializations such as property initializations. Constructors can also accept arguments, in which case, when the <code>new</code> statement is written, you also need to send the constructor arguments for the parameters.<ref name="php5cpnstructor"/>
<syntaxhighlight lang="php">
class Person
{
private string $name;
public function __construct(string $name): void
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
}
</syntaxhighlight>
Line 498 ⟶ 519:
</syntaxhighlight>
==== Perl 5 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.
Line 531 ⟶ 552:
my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 );
</syntaxhighlight>
=== Python ===
In [[Python (programming language)|Python]], constructors are defined by one or both of <code>__new__</code> and <code>__init__</code> methods. A new instance is created by calling the class as if it were a function, which calls the <code>__new__</code> and <code>__init__</code> methods. If a constructor method is not defined in the class, the next one found in the class's [[C3 linearization|Method Resolution Order]] will be called.<ref>[https://docs.python.org/3/reference/datamodel.html Data model]</ref>
In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.)
<syntaxhighlight lang="pycon">
>>> class ExampleClass:
... def __new__(cls, value):
... print("Creating new instance...")
... # Call the superclass constructor to create the instance.
... instance = super(ExampleClass, cls).__new__(cls)
... return instance
... def __init__(self, value):
... print("Initialising instance...")
... self.payload = value
>>> exampleInstance = ExampleClass(42)
Creating new instance...
Initialising instance...
>>> print(exampleInstance.payload)
42
</syntaxhighlight>
Classes normally act as [[Factory (object-oriented programming)|factories]] for new instances of themselves, that is, a class is a callable object (like a function), with the call being the constructor, and calling the class returns an instance of that class. However the <code>__new__</code> method is permitted to return something other than an instance of the class for specialised purposes. In that case, the <code>__init__</code> is not invoked.<ref>[https://docs.python.org/3/reference/datamodel.html#object.__new__ Data model]</ref>
=== Raku ===
Line 584 ⟶ 630:
my $p0 = Person.new( :$first-name, :$last-name, :$age );
</syntaxhighlight>
=== Ruby ===
Line 646:
</syntaxhighlight>
===
In [[Visual Basic .NET]], constructors use a method declaration with the name "<code>New</code>".
<syntaxhighlight lang="
Class Foobar
Private strData As String
Public Sub New(ByVal someParam As String)
strData = someParam
End Sub
End Class
</syntaxhighlight>
<syntaxhighlight lang="vbnet">
' code somewhere else
' instantiating an object with the above constructor
Dim foo As New Foobar(".NET")
</syntaxhighlight>
|