Constructor (object-oriented programming)
Special function called to create an object
title: "Constructor (object-oriented programming)" type: doc version: 1 created: 2026-02-28 author: "Wikipedia contributors" status: active scope: public tags: ["method-(computer-programming)", "programming-language-comparisons"] description: "Special function called to create an object" topic_path: "general/method-computer-programming" source: "https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)" license: "CC BY-SA 4.0" wikipedia_page_id: 0 wikipedia_revision_id: 0
::summary Special function called to create an object ::
In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.
A constructor resembles an instance method, but it differs from a method in that it has no explicit return type, it is not implicitly inherited and it usually has different rules for scope modifiers. Constructors often have the same name as the declaring class. They have the task of initializing the object's data members and of establishing the invariant of the class, failing if the invariant is invalid. A properly written constructor leaves the resulting object in a valid state. Immutable objects must be initialized in a constructor.
Most languages allow overloading the constructor in that there can be more than one constructor for a class, with differing parameters. Some languages take consideration of some special types of constructors. Constructors, which concretely use a single class to create objects and return a new instance of the class, are abstracted by factories, which also create objects but can do so in various ways, using multiple classes or different allocation schemes such as an object pool.
Types
Parameterized constructors
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.
::code[lang=cpp] class Point { private: int x; int y; public: Point() = default; Point(int x, int y): x{x}, y{y} {} // Parameterized constructor }; ::
::code[lang=cpp] Point p = Point(0, 50); // Explicit call. Point p2(0, 50); // Implicit call. ::
Default constructors
If the programmer does not supply a constructor for an instantiable class, Java compiler inserts a default constructor into the code. This constructor is known as default constructor. It would not be found in source code (the file) as it would be inserted into the code during compilation and exists in 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), etc.
::code[lang=cpp] class Point { private: int x; int y; public: Point(int x = 0, int y = 0); // Default constructor. }; ::
Copy constructors
Like C++, Java also supports "Copy Constructors". But, unlike C++, Java does not create a default copy constructor even if no such copy constructor is specified. Copy constructors define the actions performed by the compiler when copying class objects. A Copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object). It is used to create a copy of an existing object of the same class. Even though both classes are the same, it counts as a conversion constructor. While copy constructors are usually abbreviated copy ctor or cctor, they have nothing to do with class constructors used in .NET using the same abbreviation.
Conversion constructors
Conversion constructors provide a means for a compiler to implicitly create an object belonging to one class based on an object of a different type. These constructors are usually invoked implicitly to convert arguments or operands to an appropriate type, but they may also be called explicitly.
Move constructors
In C++, move constructors take an Rvalue reference to an object of the class, and are used to implement ownership transfer of the parameter object's resources.
Syntax
- Java, C++, C#, ActionScript, PHP 4, and MATLAB have a naming convention in which constructors have the same name as the class with which they are associated.
- In Rust, the convention for the "constructor" is to name it
new. - In PHP 5, a recommended name for a constructor is
__construct. For backwards compatibility, a method with the same name as the class will be called if__constructmethod can not be found. Since PHP 5.3.3, this works only for non-namespaced classes. - In PHP 7, you should always name the constructor as
__construct. Methods with the same name as the class will trigger an E_DEPRECATED level error. - In Perl, constructors are, by convention, named "new" and have to do a fair amount of object creation.
- In Moose object system for Perl, constructors (named new) are automatically created and are extended by specifying a BUILD method.
- In Visual Basic .NET, the constructor is called "
New". - In Python, the constructor is split over two methods, "
__new__" and "__init__". The__new__method is responsible for allocating memory for the instance, and receives the class as an argument (conventionally called "cls"). The__init__method (often called "the initialiser") is passed the newly created instance as an argument (conventionally called "self"). - Object Pascal constructors are signified by the keyword "
constructor" and can have user-defined names (but are mostly called "Create"). - In Objective-C, the constructor method is split across two methods, "
alloc" and "init" with theallocmethod setting aside (allocating) memory for an instance of the class, and theinitmethod handling the bulk of initializing the instance. A call to the method "new" invokes both theallocand theinitmethods, for the class instance.
Memory organization
In Java, C#, and VB .NET, the constructor creates reference type objects on the heap, whereas primitive types (such as int, double, etc.) are stored on the stack (though some languages allow for manually allocating objects on the stack through a stackalloc modifier). 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 these languages, object destruction occurs when the object has no references and then gets destroyed by the garbage collector.
In C++, objects are created on the stack when the constructor is invoked without the new operator, and created on the heap when the constructor is invoked with the new 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 delete operator. By using the "Resource Acquisition is Initialization" (RAII) idiom, resource management can be greatly simplified.
Notes
References
References
- [http://www.php.net/manual/en/language.oop5.decon.php Constructors and Destructors], from PHP online documentation
- [https://docs.python.org/3/reference/datamodel.html#basic-customization Data model], from Python online documentation
- https://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order Constructor
- (23 June 2023). "Target-typed new expressions". Microsoft Learn.
- Albahari, Joseph. "C# 10 in a Nutshell". O'Reilly.
- (2013-02-06). "Fabulous Adventures in Coding". Eric Lippert.
- (2006-01-01). "Expert .NET 2.0 IL Assembler". APress.
- "Download Visual Studio 2005 Retired documentation from Official Microsoft Download Center".
- Skeet, Jon. (23 March 2019). "C# in Depth". Manning.
- [https://wikidocs.adobe.com/wiki/display/coldfusionen/cfcomponent CFComponent]
- "Eiffel ISO/ECMA specification document".
- "Details on Constructor in java".
- (2013). "Providing Constructors for Your Classes". Oracle Corporation.
- "OCaml - The OCaml Manual".
- "3. Data model".
::callout[type=info title="Wikipedia Source"] This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page. ::