Constructor (object-oriented programming)
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.
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. class Point { private: int x; int y; public: Point() = default; Point(int x, int y): x{x}, y{y} {} // Parameterized constructor }; Point p = Point(0, 50); // Explicit call. Point p2(0, 50); // Implicit call. class Point { private: int x; int y; public: Point(int x = 0, int y = 0); // Default constructor. }; include typedef struct { char* name; int age; } Person; // this method creates an instance of Person Person* createPerson(const char name[], int age) { Person* p = (Person*)malloc(sizeof(Person)); if (!p) { return NULL; } strcpy(p->name, name); p->age = age; return p; } // this method destroys an instance of Person void destroyPerson(Person* p) { if (p) { free(p->name); free(p); } } A copy constructor has a parameter of the same type passed as const reference, for example X(const X& 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. import std; class PolarPoint { private: double x; double y; public: explicit PolarPoint(double r = 1.0, double theta = 0.0): // Constructor, parameters with default values. x{r * std::cos(theta)}, y{r * std::sin(theta)} /* Example invocations: PolarPoint a; PolarPoint b(3); PolarPoint c(5, std::numbers::pi / 4); On returning objects from functions or passing objects by value, the objects copy constructor will be called implicitly, unless return value optimization applies. C++ implicitly generates a default copy constructor which will call the copy constructors for all base classes and all member variables unless the programmer provides one, explicitly deletes the copy constructor (to prevent cloning) or one of the base classes or member variables copy constructor is deleted or not accessible (private). Most cases calling for a customized copy constructor (e.g. reference counting, deep copy of pointers) also require customizing the destructor and the copy assignment operator. This is commonly referred to as the Rule of three. public class MyClass { private int a; private string b; // Constructor public MyClass() : this(42, "string") { } // Overloading a constructor public MyClass(int a, string b) { this.a = a; this.b = b; } } // Code somewhere // Instantiating an object with the constructor above MyClass c = new MyClass(42, "string"); Since C# 9.0, constructor calls can be further simplified using target-typed new expressions, which do not require naming the constructor when the type is already given. It will automatically call the constructor of the named type before the variable, but obviously will not resolve if using type deduction ( var ). // Above example with target-typed new expressions MyClass c = new(42, "string"); public class MyClass { private static int _A; // Normal constructor static MyClass() { _A = 32; } // Standard default constructor public MyClass() { } } // Code somewhere // Instantiating an object with the constructor above // right before the instantiation // The variable static constructor is executed and _A is 32 MyClass c = new MyClass(); component { // properties property name="cheeseName"; // constructor function Cheese init( required string cheeseName ) { variables.cheeseName = arguments.cheeseName; return this; } } Create instance of a cheese. myCheese = new Cheese( 'Cheddar' ); Since ColdFusion 10, CFML has also supported specifying the name of the constructor method: component initmethod="Cheese" { // properties property name="cheeseName"; // constructor function Cheese Cheese( required string cheeseName ) { variables.cheeseName = arguments.cheeseName; return this; } } class Car # the initializer, which is an instance method. def initialize(make : String, year : Int) @make = make @year = year end # the allocator, which is a class method, denoted by the "self." prefix. # note that `new` takes the same arguments as `initialize` def self.new(make : String, year : Int) # allocate memory for the instance instance = Car.allocate # call the instance's initialize method using the provided parameters instance.initialize make, year # return the instance instance end end instantiate a new `Car` like so: old_car = Car.new("Chevrolet", 1947) Although object creation involves some subtleties, the creation of an attribute with a typical declaration x: T as expressed in a creation instruction create x.make consists of the following sequence of steps: Create a new direct instance of type T . Execute the creation procedure make to the newly created instance. Attach the newly initialized object to the entity x . In the first snippet below, class POINT is defined. The procedure make is coded after the keyword feature . The keyword create introduces a list of procedures which can be used to initialize instances. In this case the list includes default_create , a procedure with an empty implementation inherited from class ANY , and the make procedure coded within the class. class POINT create default_create, make feature make (a_x_value: REAL; a_y_value: REAL) do x := a_x_value y := a_y_value end x: REAL -- X coordinate y: REAL -- Y coordinate ... In the second snippet, a class which is a client to POINT has a declarations my_point_1 and my_point_2 of type POINT . In procedural code, my_point_1 is created as the origin (0.0, 0.0). Because no creation procedure is specified, the procedure default_create inherited from class ANY is used. This line could have been coded create my_point_1.default_create . Only procedures named as creation procedures can be used in an instruction with the create keyword. Next is a creation instruction for my_point_2 , providing initial values for the my_point_2 's coordinates. The third instruction makes an ordinary instance call to the make procedure to reinitialize the instance attached to my_point_2 with different values. my_point_1: POINT my_point_2: POINT ... create my_point_1 create my_point_2.make (3.0, 4.0) my_point_2.make (5.0, 8.0) ... type MyClass(_a : int, _b : string) = class // Primary constructor let a = _a let b = _b do printfn "a = %i, b = %s" a b // Additional constructors new(_a : int) = MyClass(_a, "") then printfn "Integer parameter given" new(_b : string) = MyClass(0, _b) then printfn "String parameter given" new() = MyClass(0, "") then printfn "No parameter given" end // Code somewhere // instantiating an object with the primary constructor let c1 = new MyClass(42, "string") // instantiating an object with additional constructors let c2 = new MyClass(42) let c3 = new MyClass("string") let c4 = MyClass() // "new" keyword is optional class X { public X() { // Non-parameterized constructor this(1); // Calling of constructor System.out.println("Calling default constructor"); } public X(int a) { // Parameterized constructor System.out.println("Calling parameterized constructor"); } } public class Example { public static void main(String[] args) { X x = new X(); } } Java provides access to the superclass's constructor through the super keyword. class X { // Declaration of instance variable(s). private int data; // Definition of the constructor. public X() { this(1); } // Overloading a constructor public X(int input) { data = input; // This is an assignment } } class Y extends X { private int data2; public Y() { super(); data2 = 1; } public Y(int input1, int input2) { super(input1); data2 = input2 } } public class Example { public static void main(String[] args) { Y y = new Y(42, 43); } } A constructor taking zero number of arguments is called a "no-arguments" or "no-arg" constructor. class FooBar { constructor(baz) { this.baz = baz; } } This can be instantiated as such const foo = new FooBar('7'); The equivalent of this before ES6, was creating a function that instantiates an object as such function FooBar (baz) { this.baz = baz; } This is instantiated the same way as above. The TypeScript equivalent of this would be: class FooBar { baz: string; constructor(baz: string) { this.baz = baz; } } const foo: FooBar = new FooBar('7'); program OopProgram; type TPerson = class private FName: string; public property Name: string read FName; constructor Create(AName: string); end; constructor TPerson.Create(AName: string); begin FName := AName; end; var Person: TPerson; begin Person := TPerson.Create('Peter'); // allocates an instance of TPerson and then calls TPerson.Create with the parameter AName = 'Peter' end. class person first_name last_name = object val full_name = first_name ^ " " ^ last_name initializer print_endline("Hello there, I am " ^ full_name ^ ".") method get_last_name = last_name end;; let alonzo = new person "Alonzo" "Church" in (*Hello there, I am Alonzo Church.*) print_endline alonzo#get_last_name (*Church*) class Person { private string $name; public function __construct(string $name): void { $this->name = $name; } public function getName(): string { return $this->name; } } In PHP, a class is only allowed to declare a maximum of one constructor method. Static methods, factory classes or optional constructor arguments are some ways to facilitate multiple ways to create objects of a PHP class. package Person; In Perl constructors are named 'new' by convention. sub new { # Class name is implicitly passed in as 0th argument. my $class = shift; # Default attribute values, if you have any. my %defaults = ( foo => "bar" ); # Initialize attributes as a combination of default values and arguments passed. my $self = { %defaults, @_ }; # Check for required arguments, class invariant, etc. if ( not defined $self->{first_name} ) { die "Mandatory attribute missing in Person->new(): first_name"; } if ( not defined $self->{last_name} ) { die "Mandatory attribute missing in Person->new(): last_name"; } if ( defined $self->{age} and $self->{age} new(): age In the Moose object system for Perl, most of this boilerplate can be omitted, a default new is created, attributes can be specified, and 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. package Person; enable Moose-style object construction use Moose; first name ( a string) can only be set at construction time ('ro') has first_name => (is => 'ro', isa => 'Str', required => 1); last name ( a string) can only be set at construction time ('ro') has last_name => (is => 'ro', isa => 'Str', required => 1); age (Integer) can be modified after construction ('rw'), and is not required to be passed to be constructor. Also creates a 'has_age' method which returns true if age has been set has age => (is => 'rw', isa => 'Int', predicate => 'has_age'); Check custom requirements sub BUILD { my $self = shift; if ($self->has_age && $self->age In both cases the Person class is instiated like this: use Person; my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 ); 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 if __name__ == "__main__": exampleInstance: ExampleClass = ExampleClass(42) print(exampleInstance.payload) This prints: Creating new instance... Initialising instance... 42 Classes normally act as 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 __new__ method is permitted to return something other than an instance of the class for specialised purposes. In that case, the __init__ is not invoked. class Person { has Str $.first-name is required; # First name (a string) can only be set at # construction time (the . means "public"). has Str $.last-name is required; # Last name (a string) can only be set at # construction time (a ! would mean "private"). has Int $.age is rw; # Age (an integer) can be modified after # construction ('rw'), and is not required # during the object instantiation. # Create a 'full-name' method which returns the person's full name. # This method can be accessed outside the class. method full-name { $!first-name.tc ~ " " ~ $!last-name.tc } # Create a 'has-age' method which returns true if age has been set. # This method is used only inside the class so it's declared as "private" # by prepending its name with a ! method !has-age { self.age.defined } # Check custom requirements method TWEAK { if self!has-age && $!age The Person class is instantiated like this: 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» Alternatively, the named parameters can be specified using the colon-pair syntax in Perl 6: my $p0 = Person.new( :first-name , :last-name , :age(42) ); my $p1 = Person.new( :first-name , :last-name ); 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: my $first-name = "Sam"; my $last-name = "Ashe"; my $age = 42; my $p0 = Person.new( :$first-name, :$last-name, :$age ); irb(main):001:0> class ExampleClass irb(main):002:1> def initialize irb(main):003:2> puts "Hello there" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> ExampleClass.new Hello there => # struct Point { x: i32, y: i32, } impl Point { pub fn new(x: i32, y: i32) -> Self { Point { x, y } } } fn main() { let p: Point = Point::new(10, 20); println!("Point is at ({}, {})", p.x, p.y); } Class Foobar Private strData As String ' Constructor Public Sub New(ByVal someParam As String) strData = someParam End Sub End Class ' code somewhere else ' instantiating an object with the above constructor Dim foo As New Foobar(".NET")
References
No reference rows published for this article.
Cite this article
MLA
"Constructor (object-oriented programming)." encyclopegia.org, 2026, https://encyclopegia.org/wiki/constructor-object-oriented-programming. Accessed 24 November 2026.
Chicago
"Constructor (object-oriented programming)." encyclopegia.org. Accessed November 24, 2026. https://encyclopegia.org/wiki/constructor-object-oriented-programming.
APA
encyclopegia.org. (2026). Constructor (object-oriented programming). Retrieved November 24, 2026, from https://encyclopegia.org/wiki/constructor-object-oriented-programming
Accessed November 24, 2026 · CC BY-SA 4.0 · citation page · JSON