Conceptcore
Constructors and initialization
Also called constructor, initializer, object initialization, named constructor, factory function, zero value, init function.
A constructor runs when a program creates an object and puts the object in a valid state, or refuses to create it. Languages without constructors use zero values and creation functions.
- Applies to
- core-languages
Idea
A constructor is the code that runs when a program creates an object, and its job is to bring the new object into a valid state. Creation has two steps: the runtime allocates memory for the object, and the constructor sets its fields. A constructor that checks its arguments can refuse to finish, so code that holds an object can rely on the rules that the constructor checked, for example that a range never has its low end above its high end. Python, JavaScript, Java, C#, Kotlin, C++ and PowerShell have constructors in the language. Go, Rust and C have none, and use conventions in their place: zero values, struct literals, and ordinary functions with names such as NewRange, new or range_init.
class Range:
"""Invariant: lo <= hi."""
def __new__(cls, *args): # step 1: allocate a blank object
print("allocate", cls.__name__)
return super().__new__(cls)
def __init__(self, lo, hi): # step 2: initialize it and check the invariant
if lo > hi:
raise ValueError(f"empty range {lo}..{hi}")
self.lo, self.hi = lo, hi
print("initialized", self.lo, self.hi)
@classmethod
def parse(cls, text): # a named constructor: another way in, same checks
lo, hi = text.split("..")
return cls(int(lo), int(hi))
def __len__(self):
return self.hi - self.lo + 1
r = Range(3, 7)
print(len(r))
s = Range.parse("10..12")
print(len(s))
try:
Range(9, 1) # the constructor refuses: no broken Range ever exists
except ValueError as e:
print("refused:", e)
allocate Range
initialized 3 7
5
allocate Range
initialized 10 12
3
allocate Range
refused: empty range 9..1
Python shows the two steps as two methods. __new__ allocates a blank object of the class, and __init__ checks the arguments and sets the fields. Range.parse is a second way to create a Range, from text, and it ends by calling the class, so it goes through the same checks. Range(9, 1) allocates an object, but __init__ raises an exception, and the caller never receives a Range whose low end is above its high end.
How it works
Allocate, then initialize. Every object starts as raw memory, and the constructor turns it into a value of its class. The Python documentation describes __new__ as "Called to create a new instance of class cls." and states the split: "Because new() and init() work together in constructing objects (new() to create it, and init() to customize it), no non-None value may be returned by init()".1 Java, C# and JavaScript do the allocation in new and give the constructor an object whose fields hold default values. C++ separates the steps in its syntax: new allocates and then calls the constructor, and a local object gets its memory on the stack. Go, Rust and C have no constructor step, so the code that allocates must also give the fields their values.
Invariants start in the constructor. An invariant is a rule about the fields of an object that every method can assume, such as lo <= hi or a buffer length that never exceeds its capacity. If the constructor establishes the invariant and every method keeps it, the invariant holds for the whole life of the object, and no method needs to check it again. This is the reason for private fields: when code outside the class cannot set the fields, the constructor and the methods are the only code that can break the rule. See encapsulation. A constructor that cannot establish the invariant must stop the creation: it throws an exception in Python, Java, C#, JavaScript and C++, and the equivalent function returns an error in Go, Rust and C. See exception handling and errors as values.
The order of initialization. An object of a subclass has fields from each class in its hierarchy, and the language fixes the order in which they get their values. Java runs the superclass constructor, then the field initializers of the class, then the rest of the constructor body. The Java specification describes the steps that run "Just before a reference to the newly created object is returned as the result".2 C++ builds the base classes first and then the members, and cppreference warns that the order in the constructor has no effect: "The order of member initializers in the list is irrelevant", because "non-static data member are initialized in order of declaration in the class definition", and "Finally, the body of the constructor is executed."3 The destructor destroys the members in the reverse order, and a fixed order makes that possible. C# runs the field initializers of a class before the base constructor, and JavaScript runs the field initializers of a derived class right after super() returns.
Named constructors and factories. A language with constructors gives each class one name for creation, the class name, and overloads separate the variants only by the types of their parameters. A static method or a class method gives a variant a name of its own, such as Range.parse, Duration.ofSeconds or Money.of, and can return a cached object, a subclass, or an error in place of a new object. Constructors can also call each other: this(...) in Java, : this(...) in C# and a delegating constructor in C++ let the simple variants pass their work to the general one. See the factory method pattern and the builder pattern for designs that move creation out of the class.
Zero values and defaults. Go gives every variable the zero value of its type, and its documentation asks types to make that value useful: "Since the memory returned by new is zeroed, it's helpful to arrange when designing your data structures that the zero value of each type can be used without further initialization."4 When a type needs set-up, a function named by convention NewX creates it. Rust requires a struct literal to give every field, so no field is ever unset, and it states that a constructor is only a convention: "Associated functions that aren’t methods are often used for constructors that will return a new instance of the struct. These are often called new, but new isn’t a special name and isn’t built into the language."5 Java and C# fill fields with zero, false or null before the constructor runs, which means that a field can be read before the constructor gives it a value. C leaves the members of a local variable indeterminate unless the program initializes them.
Partly built objects. While a constructor runs, the object is not yet valid, and code that sees it at that time can see broken state. The main way this happens is a call from a constructor to a method that a subclass overrides. In Java, C# and JavaScript, the call reaches the override, which runs before the constructor of the subclass has set its own fields. In C++, the call reaches the version of the class whose constructor is running, because the object counts as an object of that class until its constructor returns. Passing this to other code from a constructor, for example to register a listener, has the same risk, and in a concurrent program another thread can see the fields before they are set. See dynamic dispatch.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript, with parameter properties that declare and set a field from a constructor parameter, and private constructors checked by the compiler. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Native | A primary constructor in the class header, init blocks and secondary constructors that delegate to it; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Idiom | DEFAULT values, NOT NULL and CHECK constraints decide the initial state of a new row and reject a row that breaks the rules. |
| Bash | Does not apply | Bash has no objects to construct. |
| PowerShell | Native | A class can define constructors, overload them and call a base constructor with base(); no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Idiom | The constructor of a custom element runs when the element is created, and attributes give its initial state. |
| CSS | Does not apply | CSS has no objects; initial values of properties are a different idea. |
| Regular expressions | Does not apply | A pattern has no objects. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | __new__ and __init__; class methods as named constructors |
| JavaScript | native | constructor, super(), field initializers, static methods |
| TypeScript | native | as JavaScript, with parameter properties |
| Java | native | constructors, this(...), initializer blocks, record compact constructors |
| Kotlin | native | primary constructors, init blocks, secondary constructors |
| C# | native | constructors, : this(...), object initializers, required members |
| Go | idiom | zero values and functions named NewX |
| Rust | idiom | struct literals, new functions, the Default trait |
| C | idiom | init and create functions, designated initializers |
| C++ | native | constructors with member initializer lists |
| Bash | n/a | no objects |
| PowerShell | native | class constructors, base() |
| SQL | idiom | DEFAULT, NOT NULL and CHECK on new rows |
| Regex | n/a | no objects |
| HTML | idiom | custom element constructors and attributes |
| CSS | n/a | no objects |
The table shows two families. Python, JavaScript, Java, C#, Kotlin, C++ and PowerShell have a constructor that the language calls on every creation, and they differ in the order in which the fields of a class hierarchy get their values. Go, Rust and C have no such hook: the code that creates a value must give the fields their values, and a library offers a function that does this and checks the arguments. Go relies on zero values that work without set-up, and Rust relies on the rule that a struct literal names every field, together with private fields that force code in other modules to call new.
Each example file shows the checks of a constructor, a second way to create the same type, and one mistake. The mistakes differ: a shared default value in Python, a call to an override from a base constructor in Java and JavaScript, a missing required member in C#, a nil map in a zero value in Go, and a missing field in Rust. The C++ file shows that the members of a class are built in the order of their declaration, and that a constructor that throws stops the creation after the members already built.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Money:
cents: int
currency: str = "EUR" # a default for an optional field
def __post_init__(self): # runs after the generated __init__
if len(self.currency) != 3:
raise ValueError(f"bad currency {self.currency!r}")
@classmethod
def of(cls, text): # a named constructor
amount, currency = text.split()
return cls(round(float(amount) * 100), currency)
@dataclass
class Order:
lines: list = field(default_factory=list) # a new list for each object
print(Money(250), Money.of("3.10 USD"))
try:
Money(1, "euro")
except ValueError as e:
print(e)
a, b = Order(), Order()
a.lines.append("tea")
print(a, b)
Money(cents=250, currency='EUR') Money(cents=310, currency='USD')
bad currency 'euro'
Order(lines=['tea']) Order(lines=[])
This code runs but gives a wrong answer on purpose.
class Order:
def __init__(self, lines=[]): # the default list is made once, with the function
self.lines = lines
a = Order()
b = Order()
a.lines.append("tea")
print(b.lines, a.lines is b.lines)
['tea'] True
- Verdict: native. Calling a class runs two methods:
__new__makes the object and__init__sets its attributes. Most classes define only__init__, and aclassmethodgives a named constructor that parses or converts its input and then calls the class. Adataclasswrites__init__from the field list, and__post_init__runs after it to check the values.field(default_factory=list)makes a new list for each object. - The wrong block uses a list as the default value of a parameter of
__init__. Python evaluates a default once, when it defines the function, so everyOrdermade without an argument shares one list. UseNoneas the default and create the list in the body, or usedefault_factoryin a dataclass.
#include <iostream>
#include <stdexcept>
#include <string>
struct Trace {
explicit Trace(const char* what) { std::cout << "init " << what << '\n'; }
};
class Range {
public:
Range(int lo, int hi) : lo_(check(lo, hi)), hi_(hi) // a member initializer list
{
std::cout << "constructor body\n";
}
explicit Range(int hi) : Range(0, hi) {} // a delegating constructor
static Range parse(const std::string& text) // a named constructor
{
auto dots = text.find("..");
return Range(std::stoi(text.substr(0, dots)), std::stoi(text.substr(dots + 2)));
}
int size() const { return hi_ - lo_ + 1; }
private:
static int check(int lo, int hi)
{
if (lo > hi) throw std::invalid_argument("empty range");
return lo;
}
Trace first_{"first_"}; // members initialize in the order of declaration
int lo_;
int hi_;
Trace last_{"last_"};
};
int main()
{
std::cout << Range(3, 7).size() << '\n';
std::cout << Range::parse("10..12").size() << '\n';
try {
Range(9, 1);
} catch (const std::invalid_argument& e) {
std::cout << e.what() << '\n';
}
}
init first_
init last_
constructor body
5
init first_
init last_
constructor body
3
init first_
empty range
This code runs but gives a wrong answer on purpose.
#include <iostream>
#include <string>
class Widget {
public:
Widget() { render(); } // a virtual call during construction
virtual ~Widget() = default;
virtual void render() const { std::cout << "widget\n"; }
};
class Label : public Widget {
public:
Label() : text_("hello") {}
void render() const override { std::cout << "label: " << text_ << '\n'; }
private:
std::string text_;
};
int main()
{
Label l; // Widget() runs while the object is still a Widget
l.render(); // after construction, the call reaches Label
}
widget
label: hello
- Verdict: native. A constructor initializes the bases and members in its member initializer list, and then runs its body. The order is fixed by the class, not by the list: bases first, then members in the order of their declaration, which the traces of
first_andlast_show. A constructor can delegate to another, andexplicitstops a one-argument constructor from acting as an implicit conversion. If a constructor throws, the members already built are destroyed and the object never exists, soRange(9, 1)buildsfirst_and then stops. - The wrong block calls a virtual function from a base constructor. While
Widget's constructor runs, the object is aWidget, so the call reachesWidget::render, not the override. After construction, the same call reachesLabel::render. The behavior is defined, unlike in Java and JavaScript, but it still surprises readers who expect the override.
import java.util.Objects;
class Base {
static { System.out.println("Base: static initializer, once per class"); }
protected final String id;
Base(String id) {
System.out.println("Base constructor");
this.id = id;
}
}
class Range extends Base {
private final int lo, hi;
private int uses = log("Range: field initializer"); // runs after super(...)
Range(int lo, int hi) {
if (lo > hi) throw new IllegalArgumentException("empty range " + lo + ".." + hi);
super("r" + lo); // a statement before super: check the arguments first
this.lo = lo;
this.hi = hi;
System.out.println("Range constructor body");
}
Range(int hi) { this(0, hi); } // delegates to another constructor
static Range parse(String text) { // a static factory
String[] parts = Objects.requireNonNull(text).split("\\.\\.");
return new Range(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
}
private static int log(String s) {
System.out.println(s);
return 0;
}
int size() { return hi - lo + 1; }
}
record Point(int x, int y) {
Point { // a compact constructor: checks run before the fields are set
if (x < 0 || y < 0) throw new IllegalArgumentException("negative coordinate");
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Range(3, 7).size());
System.out.println(Range.parse("10..12").size() + " " + new Range(4).id);
try {
new Range(9, 1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
System.out.println(new Point(1, 2));
}
}
Base: static initializer, once per class
Base constructor
Range: field initializer
Range constructor body
5
Base constructor
Range: field initializer
Range constructor body
Base constructor
Range: field initializer
Range constructor body
3 r0
empty range 9..1
Point[x=1, y=2]
This code runs but gives a wrong answer on purpose.
class Widget {
Widget() {
render(); // an overridable call from a constructor
}
void render() { System.out.println("widget"); }
}
class Label extends Widget {
private final String text;
Label(String text) {
super();
this.text = text; // too late for the call in Widget()
}
@Override
void render() { System.out.println("label: " + text); }
}
public class Main {
public static void main(String[] args) {
new Label("hello");
}
}
label: null
- Verdict: native. A constructor has the name of its class and no return type. The static initializer of a class runs once, when the class is first used. For each object, Java sets every field to its default value, runs the superclass constructor, then the field initializers of the class, then the constructor body. A constructor can delegate to another with
this(...). Statements may come before the call tosuper(...)when they do not usethis, which letsRangecheck its arguments first. A record's compact constructor checks the components before the fields are set. - The wrong block calls an overridable method from a constructor. Java dispatches the call to
Label.render, which runs beforeLabel's constructor has settext, so it prints the default valuenull, even thoughtextisfinal. Make methods called from constructorsprivate,staticorfinal.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct range {
int lo, hi;
};
/* An init function: the caller owns the memory, the function checks the values. */
static int range_init(struct range *r, int lo, int hi)
{
if (lo > hi)
return -1;
r->lo = lo;
r->hi = hi;
return 0;
}
struct buffer {
size_t len, cap;
char *data;
};
/* A create function: allocates and initializes, or returns NULL. */
static struct buffer *buffer_create(size_t cap)
{
struct buffer *b = malloc(sizeof *b);
if (b == NULL)
return NULL;
b->data = malloc(cap);
if (b->data == NULL) {
free(b); /* undo the part that succeeded */
return NULL;
}
b->len = 0;
b->cap = cap;
return b;
}
static void buffer_destroy(struct buffer *b)
{
if (b != NULL)
free(b->data);
free(b);
}
struct config {
const char *name;
int retries;
int verbose;
};
int main(void)
{
struct range r;
printf("%d ", range_init(&r, 3, 7));
printf("%d\n", range_init(&r, 9, 1));
struct config c = {.retries = 3}; /* designated: the other members are zero */
printf("%s %d %d\n", c.name == NULL ? "(null)" : c.name, c.retries, c.verbose);
struct buffer *b = buffer_create(16);
memcpy(b->data, "hi", 3);
b->len = 2;
printf("%s %zu %zu\n", b->data, b->len, b->cap);
buffer_destroy(b);
return 0;
}
0 -1
(null) 3 0
hi 2 16
- Verdict: idiom. C has no constructors. Two conventions replace them. An init function takes a pointer to memory that the caller owns, sets the fields and returns an error code. A create function allocates the memory too and returns a pointer or
NULL, and a matching destroy function frees it. A create function that fails half way must free what it has already allocated. A designated initializer sets named members and makes all the others zero, which is the closest C comes to default values. A local variable without an initializer has an indeterminate value, and reading it is undefined behavior.
var r = new Range(3, 7);
Console.WriteLine(r.Size);
Console.WriteLine(Range.Parse("10..12").Size);
try
{
_ = new Range(9, 1);
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
var p = new Person { Name = "Ana" }; // an object initializer sets init and required members
Console.WriteLine($"{p.Name} {p.Email ?? "(no email)"}");
Console.WriteLine(new Label().Text);
class Range
{
public int Lo { get; }
public int Hi { get; }
public Range(int lo, int hi)
{
if (lo > hi) throw new ArgumentException($"empty range {lo}..{hi}");
(Lo, Hi) = (lo, hi);
}
public Range(int hi) : this(0, hi) { } // delegates to another constructor
public static Range Parse(string text) // a static factory
{
var parts = text.Split("..");
return new Range(int.Parse(parts[0]), int.Parse(parts[1]));
}
public int Size => Hi - Lo + 1;
}
class Person
{
public required string Name { get; init; } // must be set when the object is created
public string? Email { get; init; }
}
class Widget
{
public string Text;
protected Widget() { Text = Render(); }
protected virtual string Render() => "widget";
}
class Label : Widget
{
private readonly string text = "hello"; // C# runs field initializers before the base constructor
protected override string Render() => "label: " + text;
}
5
3
empty range 9..1
Ana (no email)
label: hello
This code does not compile, on purpose.
var p = new Person(); // Name is required but not set
Console.WriteLine(p.Name);
class Person
{
public required string Name { get; init; }
}
- Verdict: native. A constructor can check its arguments and delegate to another with
: this(...)or call a base constructor with: base(...). Object initializers set properties after the constructor runs, andinitaccessors allow this only during creation. Arequiredmember must be set by every object initializer, which the compiler checks. C# runs the field initializers of a class before it calls the base constructor, so the virtual call fromWidget's constructor seestextalready set, unlike in Java and JavaScript. Fields set in the constructor body are still unset at that point. - The failing block creates a
Personwithout setting the requiredName, and the compiler rejects it with error CS9035.
class Base {
name = "base field"; // a field initializer runs as part of construction
constructor(id) {
console.log("Base constructor", id);
this.id = id;
}
}
class Item extends Base {
price = 0; // initialized after super() returns
constructor(id, price) {
super(id); // must come before any use of this
console.log("Item constructor, price field is", this.price);
this.price = price;
}
static free(id) { return new Item(id, 0); } // a named constructor
}
const i = new Item(7, 250);
console.log(i);
console.log(Item.free(8).price);
Base constructor 7
Item constructor, price field is 0
Item { name: 'base field', id: 7, price: 250 }
Base constructor 8
Item constructor, price field is 0
0
This code runs but gives a wrong answer on purpose.
class Widget {
constructor() {
this.render(); // calls the subclass method before the subclass is ready
}
render() { console.log("widget"); }
}
class Label extends Widget {
text = "hello"; // set only after Widget's constructor returns
render() { console.log("label:", this.text); }
}
new Label();
label: undefined
- Verdict: native.
newcreates an object whose prototype is the class'sprototype, and runs theconstructor. In a derived class, the constructor must callsuper(...)before it usesthis, and the field initializers of the derived class run right aftersuperreturns, before the rest of the constructor body. That is whyItem's constructor seespriceas 0, the value of the initializer, before it sets the real price. A static method is the usual named constructor. - The wrong block calls an overridden method from the base constructor. The call reaches
Label.render, butLabel's fieldtextgets its value only afterWidget's constructor returns, so the method seesundefined. Keep constructors free of calls to methods that subclasses can override, or start the work in a separate method after construction.
package main
import (
"bytes"
"errors"
"fmt"
"sync"
"time"
)
// The zero value is ready to use: no constructor needed.
type Counter struct {
mu sync.Mutex // the zero Mutex is unlocked
n map[string]int
}
func (c *Counter) Add(key string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.n == nil { // create the map lazily, so the zero Counter works
c.n = map[string]int{}
}
c.n[key]++
}
// A constructor is an ordinary function, by convention named NewX.
type Range struct{ lo, hi int }
func NewRange(lo, hi int) (*Range, error) {
if lo > hi {
return nil, fmt.Errorf("empty range %d..%d", lo, hi)
}
return &Range{lo, hi}, nil
}
// Functional options give a constructor optional settings with defaults.
type Server struct {
addr string
timeout time.Duration
}
type Option func(*Server)
func WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }
func NewServer(addr string, opts ...Option) (*Server, error) {
if addr == "" {
return nil, errors.New("empty address")
}
s := &Server{addr: addr, timeout: 30 * time.Second}
for _, opt := range opts {
opt(s)
}
return s, nil
}
func main() {
var b bytes.Buffer // zero value: an empty buffer
b.WriteString("ready")
var c Counter
c.Add("x")
c.Add("x")
fmt.Println(b.String(), c.n["x"])
r, err := NewRange(3, 7)
fmt.Println(*r, err)
_, err = NewRange(9, 1)
fmt.Println(err)
s, _ := NewServer(":8080", WithTimeout(5*time.Second))
fmt.Println(s.addr, s.timeout)
}
ready 2
{3 7} <nil>
empty range 9..1
:8080 5s
This code panics, on purpose.
package main
import "fmt"
type Index struct {
words map[string]int // nil in the zero value
}
func (ix *Index) Add(w string) { ix.words[w]++ }
func main() {
var ix Index // no constructor ran
ix.Add("go")
fmt.Println(ix.words)
}
- Verdict: idiom. Go has no constructors. Every variable starts at the zero value of its type, and good Go types make that value useful: an empty
bytes.Bufferis ready to write, and a zerosync.Mutexis unlocked. When a type needs set-up or checks, its package gives a function by convention namedNewX, which returns a pointer and often an error. Functional options pass optional settings to such a function, with defaults set first. - The failing block uses the zero value of a struct that holds a map. A zero map is
nil: it can be read but not written, so the firstAddpanics. Create the map in aNewIndexfunction, or create it lazily in the method, asCounterdoes in the run block.
#[derive(Debug)]
struct Range {
lo: i32,
hi: i32,
}
impl Range {
// No constructors in the language: `new` is an ordinary function by convention.
fn new(lo: i32, hi: i32) -> Result<Range, String> {
if lo > hi {
return Err(format!("empty range {lo}..{hi}"));
}
Ok(Range { lo, hi }) // a struct literal must give every field
}
fn size(&self) -> i32 {
self.hi - self.lo + 1
}
}
#[derive(Default)]
struct Config {
name: String, // Default gives ""
retries: u32, // 0
verbose: bool, // false
}
fn main() {
println!("{:?}", Range::new(3, 7).map(|r| r.size()));
println!("{:?}", Range::new(9, 1));
let c = Config {
retries: 3,
..Default::default()
}; // the rest from Default
println!("{:?} {} {}", c.name, c.retries, c.verbose);
}
Ok(5)
Err("empty range 9..1")
"" 3 false
This code does not compile, on purpose. The error is E0063.
struct Range {
lo: i32,
hi: i32,
}
fn main() {
let r = Range { lo: 3 }; // hi is missing
println!("{}", r.lo);
}
- Verdict: idiom. Rust has no constructors. A struct literal creates a value and must give every field, so no value has a field that was never set. By convention, an associated function
newchecks the arguments and returns the value or aResult. TheDefaulttrait gives a value with default fields, and the update syntax..Default::default()fills the fields that a literal does not name. Private fields stop code in other modules from writing a literal at all, sonewbecomes the only way in. - The failing block writes a struct literal without the field
hi, and the compiler reports error E0063.
Variations and related ideas
- Default, copy and move constructors. C++ creates these for a class unless the class declares its own, and they decide how objects are created without arguments, copied and moved. See ownership.
- Primary constructors. Kotlin, Scala and C# can declare the constructor parameters in the class header, and records in Java and C# derive the constructor from the component list.
- Object initializers and builders. C# object initializers and Kotlin named arguments set many properties at creation without a constructor for each combination. A builder collects the settings step by step and checks them in one final call. See the builder pattern.
- Two-phase initialization. Objective-C separates
allocandinitinto two messages, and Swift checks in its compiler that an initializer sets every stored property before it usesself. - Destructors and finalizers. The opposite of a constructor runs when an object goes away. In C++ and Rust it runs at a known point, which lets constructors acquire resources that destructors release. See resource acquisition is initialization.
- Factories and dependency injection. A factory or a container creates objects and passes them their dependencies, so the class does not choose its collaborators. See the factory method pattern.
- Lazy initialization. A field gets its value on first use, not in the constructor, as
Counterdoes with its map in the Go file. - Prototypes. In a language without classes, a new object copies a prototype or delegates to it, and a function sets its fields. See prototype-based programming.
- Immutable objects. An object whose fields cannot change after construction needs all its values in the constructor, so the constructor is the only place to check them. See immutability.
Pitfalls
- Calls to overridable methods. A base constructor that calls an overridden method runs code of the subclass before the subclass has set its fields. The wrong blocks in the Java and JavaScript files print
nullandundefined, and the C++ file shows a call that never reaches the override. Call only private or final methods from a constructor. - Shared default values. A default argument that is a mutable object, such as a list in Python, is created once and shared by every object made without that argument. The wrong block in the Python file shows this.
- Work in constructors. A constructor that opens network connections, reads files or starts threads is slow, hard to test and can fail in ways that leave resources open. Keep constructors to checks and assignments, and pass in the resources the object needs.
- Leaking
this. Code that storesthisin a global list or passes it to another thread from inside the constructor exposes an object that is not ready. Register the object after construction. - Initialization order across members. In C++ a member initializer that reads another member reads it before its construction when the other member comes later in the class. Declare members in the order in which they depend on each other, and let the compiler warn about mismatches.
- Unusable zero values. In Go, a zero value that holds a nil map panics on the first write, and the failing block in the Go file shows this. Make zero values usable, or make the type unexported and offer a
NewXfunction. - Half-built objects in C. A create function that fails part way must free what it already allocated, or it leaks. Free in the reverse order of allocation, as
buffer_createin the C file does. - Null fields. In Java and C#, a field that the constructor forgets to set stays
null. Usefinalandreadonlyfields, required members or nullable reference types, so that the compiler finds the omission. See null references.
Cost
A constructor costs one call plus the work of its body, and compilers inline small constructors, so creating an object costs about as much as writing its fields. The allocation is a separate cost: a heap allocation and later a collection or a free for objects on the heap, nothing more than a stack adjustment for local objects in C++, Rust, Go and C. Java and C# write the zero values first and then the real values, which writes each field twice unless the compiler removes the first store. Checks in a constructor cost a comparison or two per creation, and they save the cost of checks in every method. Factory functions that return cached objects avoid allocations for common values, as Integer.valueOf in Java does for small numbers.
History
Simula 67 gave each class a body of statements that ran when the program created an object, and this body did the work of a constructor. Smalltalk-80 created objects by sending a message such as new to a class, so creation was an ordinary method of the class. Bjarne Stroustrup added constructors and destructors to C in C with Classes, a project that he began in 1979, and C++ named the constructor after its class and added member initializer lists. Objective-C used separate alloc and init messages.
Java, from 1996, took the C++ form of the constructor and added the rule that every field has a default value before the constructor runs. C#, from 2002, did the same and added object initializers in 2007 and required members in 2022. Python 2.2, in 2001, added __new__ to the existing __init__. Go, from 2009, and Rust, from 2015, left constructors out of the language, Go in favor of zero values and Rust in favor of struct literals and new functions by convention. Java 25, in 2025, let a constructor run statements before its call to super(...), so a constructor can check its arguments before the superclass constructor runs.
References
- Data model, The Python Language Reference, 3.3.1 Basic customization, object.__new__ and object.__init__
- Chapter 12, Execution, The Java Language Specification, Java SE 25 Edition, 12.5 Creation of New Class Instances
- Constructors and member initializer lists, cppreference.com, Initialization order
- Effective Go, Allocation with new; Constructors and composite literals
- Using Structs to Structure Related Data, Method Syntax, The Rust Programming Language, Associated Functions
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag PV48PE Edit this page History Report an error Markdown