Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
m code(the->code (the - Fix a typo in one click
Tags: Mobile edit Mobile web edit Advanced mobile edit
m Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags
Line 13:
Constructors that can take at least one argument are termed as parameterized constructors. When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly. The method of calling the constructor implicitly is also called the shorthand method. If we want to initialize fields of the class with your own values, then use a parameterized constructor.
 
<sourcesyntaxhighlight lang="cpp">
class Example {
public:
Line 27:
 
Example::Example(int x, int y) : x_(x), y_(y) {}
</syntaxhighlight>
</source>
 
<sourcesyntaxhighlight lang="cpp">
Example e = Example(0, 50); // Explicit call.
Example e2(0, 50); // Implicit call.
</syntaxhighlight>
</source>
 
=== Default constructors ===
If the programmer does not supply a constructor for an instantiable class, Java compiler inserts a default constructor into your code on your behalf. This constructor is known as default constructor. You would not find it in your source code (the java file) as it would be inserted into the code during compilation and exists in .class file. The behavior of the default constructor is language dependent. It may initialize data members to zero or other same values, or it may do nothing at all. In Java, a "default constructor" refer to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class or in the absence of any programmer-defined constructors (e.g. in Java, the default constructor implicitly calls the superclass's nullary constructor, then executes an empty body). All fields are left at their initial value of 0 (integer types), 0.0 (floating-point types), false (boolean type), or null (reference types).
 
<sourcesyntaxhighlight lang="cpp">
#include <iostream>
 
Line 47:
int b;
};
</syntaxhighlight>
</source>
 
=== Copy constructors ===
Line 104:
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>
 
<sourcesyntaxhighlight lang="java">
class Example
{
Line 121:
Example e = new Example();
}
</syntaxhighlight>
</source>
 
Java provides access to the [[superclass (computer science)|superclass's]] constructor through the <code>super</code> keyword.
 
<sourcesyntaxhighlight lang="java">
public class Example
{
Line 143:
private int data;
}
</syntaxhighlight>
</source>
 
<sourcesyntaxhighlight lang="java">
// Code somewhere else
// Instantiating an object with the above constructor
Example e = new Example(42);
</syntaxhighlight>
</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>
Line 157:
As of ES6, [[JavaScript]] has direct constructors like many other programming languages. They are written as such
 
<sourcesyntaxhighlight lang="javascript">
class FooBar {
constructor(baz) {
Line 163:
}
}
</syntaxhighlight>
</source>
 
This can be instantiated as such
 
<sourcesyntaxhighlight lang="javascript">
const foo = new FooBar('7')
</syntaxhighlight>
</source>
 
The equivalent of this before ES6, was creating a function that instantiates an object as such
 
<sourcesyntaxhighlight lang="javascript">
function FooBar (baz) {
this.baz = baz;
}
</syntaxhighlight>
</source>
 
This is instantiated the same way as above.
Line 185:
In [[Visual Basic .NET]], constructors use a method declaration with the name "<code>New</code>".
 
<sourcesyntaxhighlight lang="vbnet">
Class Foobar
Private strData As String
Line 194:
End Sub
End Class
</syntaxhighlight>
</source>
 
<sourcesyntaxhighlight lang="vbnet">
' code somewhere else
' instantiating an object with the above constructor
Dim foo As New Foobar(".NET")
</syntaxhighlight>
</source>
 
=== C# ===
Line 206:
Example [[C Sharp (programming language)|C#]] constructor:
 
<sourcesyntaxhighlight lang="csharp">
public class MyClass
{
Line 224:
}
}
</syntaxhighlight>
</source>
 
<sourcesyntaxhighlight lang="csharp">
// Code somewhere
// Instantiating an object with the constructor above
MyClass c = new MyClass(42, "string");
</syntaxhighlight>
</source>
 
==== C# static constructor ====
Line 240:
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.
 
<sourcesyntaxhighlight lang="csharp">
public class MyClass
{
Line 257:
}
}
</syntaxhighlight>
</source>
 
<sourcesyntaxhighlight lang="csharp">
// Code somewhere
// Instantiating an object with the constructor above
Line 265:
// The variable static constructor is executed and _A is 32
MyClass c = new MyClass();
</syntaxhighlight>
</source>
 
=== C++ ===
Line 277:
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.
 
<sourcesyntaxhighlight lang="cpp">
class Foobar {
public:
Line 291:
double y_;
};
</syntaxhighlight>
</source>
Example invocations:
<sourcesyntaxhighlight lang="cpp">
Foobar a,
b(3),
c(5, M_PI/4);
</syntaxhighlight>
</source>
 
On returning objects from functions or passing objects by value, the objects copy constructor will be called implicitly, unless [[return value optimization]] applies.
Line 307:
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.
 
<sourcesyntaxhighlight lang="fsharp">
type MyClass(_a : int, _b : string) = class
// Primary constructor
Line 324:
printfn "No parameter given"
end
</syntaxhighlight>
</source>
 
<sourcesyntaxhighlight lang = "fsharp">
// Code somewhere
// instantiating an object with the primary constructor
Line 335:
let c3 = new MyClass("string")
let c4 = MyClass() // "new" keyword is optional
</syntaxhighlight>
</source>
 
=== Eiffel ===
Line 358:
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.
 
<sourcesyntaxhighlight lang="eiffel">
class
POINT
Line 378:
-- Y coordinate
...
</syntaxhighlight>
</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>.
Line 387:
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.
 
<sourcesyntaxhighlight lang="eiffel">
my_point_1: POINT
my_point_2: POINT
Line 396:
my_point_2.make (5.0, 8.0)
...
</syntaxhighlight>
</source>
 
=== CFML ===
Line 403:
 
'''Cheese.cfc'''
<sourcesyntaxhighlight lang="javascript">
component {
// properties
Line 414:
}
}
</syntaxhighlight>
</source>
 
Create instance of a cheese.
<sourcesyntaxhighlight lang="javascript">
myCheese = new Cheese( 'Cheddar' );
</syntaxhighlight>
</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:
 
<sourcesyntaxhighlight lang="javascript">
component initmethod="Cheese" {
// properties
Line 434:
}
}
</syntaxhighlight>
</source>
 
=== Object Pascal ===
Line 440:
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>.
 
<sourcesyntaxhighlight lang="delphi">
program OopProgram;
 
Line 462:
Person := TPerson.Create('Peter'); // allocates an instance of TPerson and then calls TPerson.Create with the parameter AName = 'Peter'
end.
</syntaxhighlight>
</source>
 
=== Perl 5 ===
Line 468:
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.
 
<sourcesyntaxhighlight lang="perl">
package Person;
# In Perl constructors are named 'new' by convention.
Line 497:
}
1;
</syntaxhighlight>
</source>
 
=== Perl 5 with Moose ===
Line 503:
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.
 
<sourcesyntaxhighlight lang="perl">
package Person;
# enable Moose-style object construction
Line 525:
}
1;
</syntaxhighlight>
</source>
 
In both cases the Person class is instiated like this:
<sourcesyntaxhighlight lang="perl">
use Person;
my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 );
</syntaxhighlight>
</source>
 
=== Perl 6 ===
Line 537:
With Perl 6, even more boilerplate can be left out, given that a default ''new'' method is inherited, attributes can be specified, as well as whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a ''BUILD'' method which will get called to allow for custom initialization. A ''TWEAK'' method can be specified to post-process any attributes already (implicitly) initialized.
 
<sourcesyntaxhighlight lang="perl6">
class Person {
has Str $.first-name is required; # First name (a string) can only be set at
Line 563:
}
}
</syntaxhighlight>
</source>
 
The Person class is instantiated like this:
<sourcesyntaxhighlight lang="perl6">
my $p0 = Person.new( first-name => 'Sam', last-name => 'Ashe', age => 42 );
my $p1 = Person.new( first-name => 'grace', last-name => 'hopper' );
say $p1.full-name(); # OUTPUT: «Grace Hopper␤»
</syntaxhighlight>
</source>
 
Alternatively, the named parameters can be specified using the colon-pair syntax in Perl 6:
<sourcesyntaxhighlight lang="perl6">
my $p0 = Person.new( :first-name<Sam>, :last-name<Ashe>, :age(42) );
my $p1 = Person.new( :first-name<Grace>, :last-name<Hopper> );
</syntaxhighlight>
</source>
 
And should you have set up variables with names identical to the named parameters, you can use a shortcut that will use the '''name''' of the variable for the named parameter:
<sourcesyntaxhighlight lang="perl6">
my $first-name = "Sam";
my $last-name = "Ashe";
my $age = 42;
my $p0 = Person.new( :$first-name, :$last-name, :$age );
</syntaxhighlight>
</source>
 
=== PHP ===
Line 590:
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"/>
 
<sourcesyntaxhighlight lang="php">
class Person
{
Line 605:
}
}
</syntaxhighlight>
</source>
 
=== Python ===
Line 613:
In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.)
 
<sourcesyntaxhighlight lang="pycon">
>>> class ExampleClass(object):
... def __new__(cls, value):
Line 628:
>>> print(exampleInstance.payload)
42
</syntaxhighlight>
</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>
Line 635:
 
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.
<sourcesyntaxhighlight lang="rbcon">
irb(main):001:0> class ExampleClass
irb(main):002:1> def initialize
Line 645:
Hello there
=> #<ExampleClass:0x007fb3f4299118>
</syntaxhighlight>
</source>
 
=== OCaml ===
Line 652:
<ref>[http://caml.inria.fr/pub/docs/manual-ocaml/index.html OCaml manual]</ref>
 
<sourcesyntaxhighlight lang="ocaml">
class person first_name last_name =
object
Line 666:
 
print_endline alonzo#get_last_name (*Church*)
</syntaxhighlight>
</source>
 
== See also ==