Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
 
(6 intermediate revisions by 2 users not shown)
Line 33:
 
<syntaxhighlight lang="cpp">
import std;
 
class Point {
private:
Line 68 ⟶ 66:
 
== Memory organization ==
In Java, C#, and VB .NET, the constructor creates reference type objects on the heap, whereas primitive types (such as <code>int</code>, <code>double</code>, etc.) are stored on the [[Stack-based memory allocation|stack]] (though some languages allow for manually allocating objects on the stack through a <code>stackalloc</code> modifier). VB .NET and C# also allow the use of the <code>new</code> operator to create value type objects, but these value type objects are created on the stack regardless of whether the operator is used or not. In these languages, object destruction occurs when the object has no references and then gets destroyed by the garbage collector.
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]]".
VB .NET and C# also allow the use of the ''new'' operator to create value type objects, but these value type objects are created on the stack regardless of whether the operator is used or not.
 
In C++, objects are created on the stack when the constructor is invoked without the <code>new</code> operator, and created on the heap when the constructor is invoked with the <code>new</code> operator (which returns a pointer to the object). Stack objects are deleted implicitly when they go out of scope, while heap objects must be deleted implicitly by a destructor or explicitly by using the ''<code>delete''</code> operator. By using the "[[Resource Acquisition is Initialization]]" (RAII) idiom, resource management can be greatly simplified.
 
== Language details ==<!-- see also Category:Programming language comparisons -->
Line 87 ⟶ 83:
 
<syntaxhighlight lang="cpp">
import std;
 
class PolarPoint {
private:
Line 102 ⟶ 100:
PolarPoint a;
PolarPoint b(3);
PolarPoint c(5, std::numbers::pi / 4);
</syntaxhighlight>
 
Line 176 ⟶ 174:
 
'''Cheese.cfc'''
<syntaxhighlight lang="javascriptcfc">
component {
// properties
Line 190 ⟶ 188:
 
Create instance of a cheese.
<syntaxhighlight lang="javascriptcfc">
myCheese = new Cheese( 'Cheddar' );
</syntaxhighlight>
Line 196 ⟶ 194:
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="javascriptcfc">
component initmethod="Cheese" {
// properties
Line 322 ⟶ 320:
public X() { // Non-parameterized constructor
this(1); // Calling of constructor
System.out.println("0-arg-consCalling default constructor");
}
 
public X(int a) { // Parameterized constructor
System.out.println("1-arg-consCalling parameterized constructor");
}
}
Line 378 ⟶ 376:
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/TypeScript ===
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>
Line 392 ⟶ 390:
 
<syntaxhighlight lang="javascript">
const foo = new FooBar('7');
</syntaxhighlight>
 
Line 399 ⟶ 397:
<syntaxhighlight lang="javascript">
function FooBar (baz) {
this.baz = baz;
}
</syntaxhighlight>
 
This is instantiated the same way as above.
 
The [[TypeScript]] equivalent of this would be:
</syntaxhighlight lang="typescript">
class FooBar {
baz: string;
 
constructor(baz: string) {
this.baz = baz;
}
}
 
const foo: FooBar = new FooBar('7');
</syntaxhighlight>
 
=== Object Pascal ===
Line 545 ⟶ 556:
In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.)
 
<syntaxhighlight lang="pyconpython">
>>> class ExampleClass:
... def __new__(cls: type, value: int) -> 'ExampleClass':
... print("Creating new instance...")
... # Call the superclass constructor to create the instance.
... instance: 'ExampleClass' = super(ExampleClass, cls).__new__(cls)
... return instance
 
... def __init__(self, value: int) -> None:
... print("Initialising instance...")
... self.payload: int = value
>>> exampleInstance = ExampleClass(42)
 
if __name__ == "__main__":
>>> exampleInstance: ExampleClass = ExampleClass(42)
>>> print(exampleInstance.payload)
</syntaxhighlight>
 
This prints:
<pre>
Creating new instance...
Initialising instance...
>>> print(exampleInstance.payload)
42
</pre>
</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 name="auto"/>