Most languages provide a default constructor if the programmer does not. However, this default constructor is overridden by an explicit 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.
==Language details and examples==
=== Java ===
=== C# ===
InExample [[C Sharp (programming language)|C#]], a constructor is this.:
<source lang="csharp">
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 beare called once and call is made implicitly bywhen the run-timeclass right before theis 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 onat every new generic instantiation one per type. (staticStatic variables are instantiated as well).
<source lang="csharp">
=== C++ ===
In [[C++]], the name of the constructor is the name of the class. It doesreturns not return anythingnothing. It can have parameters, like any [[member function]]s (methods). Constructor functions should beare declared in the public section.
The constructor has two parts. First is the [[initializer list]] which comes afterfollows the [[parameter (computer science)|parameter list]] and before the opening curly bracket of the method's body. It starts with a colon and separatedentries byare commascomma-separated. YouThe areinitializer list is not always required to have initializer list, but it givesoffers the opportunity to constructprovide values for data members withand parametersavoid soseparate youassignment can save time (one construction instead of a construction and an assignment)statements. Sometimes you must haveThe initializer list foris examplerequired if you have ''const'' or reference type data members, or members that cannotdo be default constructed (they don'tnot have parameterless constructor) logic. TheAssignments orderoccur ofaccording the list should beto the order of the declarationinitializer of the data members, because the execution order is thatlist. The second part is the body, which is a normal method body surroundedenclosed byin curly brackets.
C++ allows more than one constructor. The other constructors cannot be called, but can have different default values for the parameters. The constructor of a [[base class]] (or base classes) can also be called by a derived class. Constructor functions cannotare benot inherited and their addresses cannot be referredreferenced. When memory allocation is required, the operators ''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 implementedprovided by handexplicitly, 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">
c(5, M_PI/4);
</source>
You can write a privatePrivate data member functionfunctions appear at the top section before writing the public specifier.
If you no longer have access to a constructor then you can use the destructor.{{Clarify}}
In C++ the 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 the programmer does not. That is overridden by any explicit constructor. The default copy constructor ONLY makes member-wise copy or shallow copies. For deep copies aan programmer writtenexplicit copy constructor that makes deep copies is required. For a class to make deep copies, the three methods below must be provided.
# Copy constructor
=== 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 .<ref>[http://www.gotw.ca/gotw/066.htm].</ref>
=== F# ===
=== 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 anno 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 directlyexplicitly 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>
=== 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 thearguements function parameters in betweenfor the parenthesesparameters.<ref name="php5cpnstructor"/>
<source lang="php">
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;
=== Python ===
In [[Python (programming language)|Python]], constructors are created by defining ana __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.
=== Ruby ===
In [[Ruby (programming language)|Ruby]], constructors are created by defining a method called <code>initialize</code>. This method is executed everytimeto ainitialize each new instance is created.
<source lang="ruby">
class ExampleClass
|