Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
Line 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 -->