Skip to main content

Constructors — Default, Parameterized, Copy

Editorial

Introduction

Classes and Objects — Blueprint vs Instance showed that a class is a blueprint and an object is one thing made from it. It left one question open: when an object is made, how does it get its starting values?

When you write BankAccount("Alice", 5000.0), something has to put "Alice" into the account's owner and 5000.0 into its balance. That something is the constructor, a special method that runs by itself each time an object is made.

A constructor decides three things about every new object: what data it must be given (every bank account needs an owner), what it may leave out and get a sensible default for (a balance that starts at 0), and what it refuses (an empty owner's name, say). Because it runs before anyone can use the object, a careful constructor means an invalid object is never made. Encapsulation — Data Hiding Done Right builds on that idea.

What is a Constructor?

A constructor is a special method with four things that set it apart.

It runs by itself when an object is made. You don't call it the way you call other methods; making the object runs it.

It sets up the object's state, giving each attribute its starting value.

It has its own name: in Java, the name of the class; in Python, __init__.

It returns nothing. The Java tutorial puts it this way: "Constructor declarations look like method declarations", "except that they use the name of the class and have no return type." Python's __init__ runs after the object has been created and before it is handed back to the caller, and returning anything other than None from it is an error.

A hospital's admissions desk is a fair picture of it. Before a patient can be treated, the desk takes their name, date of birth and insurance details and gives them a room. Nobody is in the hospital's system without going through that desk first, and a constructor plays that desk for objects.

There are three main kinds of constructor, and the picture sets them side by side.

Three constructors, each run as an object is made; pick by what the object needs to be valid. 1. Default, no arguments: ShoppingCart() makes an empty cart with items = [], total = 0.0 and is_checked_out = False; use when an empty start is valid. 2. Parameterized, it takes data and checks it: User("alice_dev", ...) passes three checks, username not empty, email has "@", role is valid, and the object is made, while User("", "no-email") is refused with Username cannot be empty and no object is made; the most common kind, so no invalid object is made. 3. Copy, a new object from an existing one: GameCharacter.copy(hero) makes saved_state; after a battle the hero has hp=60 and Sword, Shield, Potion while the snapshot kept hp=100 and Sword, Shield; use for save, undo and test snapshots. Below, the copy trap in memory. Shallow copy, one list for both: with self.inventory = other.inventory, hero and saved_state point at the same list, so when the hero picks up a Potion the copy has it too. Copy the list, each has its own: with list(other.inventory), the hero's list holds Sword, Shield, Potion and the copy keeps its two, Sword and Shield.

Default Constructor: The Zero-Argument Setup

A default constructor takes no arguments (apart from the object itself, self in Python and this in Java) and gives every attribute a starting value of its own choosing. Use one when an object can sensibly start out blank: a shopping cart starts empty, a counter starts at zero.

class ShoppingCart:
    """A shopping cart that starts empty: a default constructor."""

    def __init__(self) -> None:
        # Default constructor: no parameters, every attribute gets its starting value
        self.items: list[str] = []      # starts empty
        self.total: float = 0.0         # starts at zero
        self.is_checked_out: bool = False

    def add_item(self, item: str, price: float) -> None:
        self.items.append(item)
        self.total += price
        print(f"Added '{item}' (${price:.2f}). Cart total: ${self.total:.2f}")

    def get_item_count(self) -> int:
        return len(self.items)


# Each call makes a new, empty cart; neither needs any arguments
cart1 = ShoppingCart()
cart2 = ShoppingCart()

cart1.add_item("Keyboard", 89.99)
cart1.add_item("Mouse", 29.99)

print(f"Cart 1 items: {cart1.get_item_count()}")
print(f"Cart 2 items: {cart2.get_item_count()}")  # still empty: its own list
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

// A shopping cart that starts empty: a default constructor
public class ShoppingCart {
    private final List<String> items;
    private double total;
    private boolean isCheckedOut;

    // Default constructor: no parameters, every field gets its starting value
    public ShoppingCart() {
        this.items = new ArrayList<>(); // starts empty
        this.total = 0.0;               // starts at zero
        this.isCheckedOut = false;
    }

    public void addItem(String item, double price) {
        items.add(item);
        total += price;
        System.out.printf(Locale.ROOT, "Added '%s' ($%.2f). Cart total: $%.2f%n",
                item, price, total);
    }

    public int getItemCount() {
        return items.size();
    }

    public boolean isCheckedOut() {
        return isCheckedOut;
    }

    public static void main(String[] args) {
        // Each 'new' makes a new, empty cart; neither needs any arguments
        ShoppingCart cart1 = new ShoppingCart();
        ShoppingCart cart2 = new ShoppingCart();

        cart1.addItem("Keyboard", 89.99);
        cart1.addItem("Mouse", 29.99);

        System.out.println("Cart 1 items: " + cart1.getItemCount());
        // still empty: its own list
        System.out.println("Cart 2 items: " + cart2.getItemCount());
    }
}
#include <cstdio>
#include <string>
#include <vector>

// A shopping cart that starts empty: a default constructor
class ShoppingCart {
public:
    // Default constructor: no parameters, every member gets its starting value
    ShoppingCart() : items_(), total_(0.0), isCheckedOut_(false) {}

    void addItem(const std::string& item, double price) {
        items_.push_back(item);
        total_ += price;
        std::printf("Added '%s' ($%.2f). Cart total: $%.2f\n", item.c_str(), price,
                    total_);
    }

    std::size_t getItemCount() const { return items_.size(); }
    bool isCheckedOut() const { return isCheckedOut_; }

private:
    std::vector<std::string> items_;  // starts empty
    double total_;                    // starts at zero
    bool isCheckedOut_;
};

int main() {
    // Each declaration makes a new, empty cart; neither needs any arguments
    ShoppingCart cart1;
    ShoppingCart cart2;

    cart1.addItem("Keyboard", 89.99);
    cart1.addItem("Mouse", 29.99);

    std::printf("Cart 1 items: %zu\n", cart1.getItemCount());
    // still empty: its own list
    std::printf("Cart 2 items: %zu\n", cart2.getItemCount());
    return 0;
}
// A shopping cart that starts empty: a default constructor
class ShoppingCart {
  private readonly items: string[];
  private total: number;
  private checkedOut: boolean;

  // Default constructor: no parameters, every field gets its starting value
  constructor() {
    this.items = []; // starts empty
    this.total = 0.0; // starts at zero
    this.checkedOut = false;
  }

  addItem(item: string, price: number): void {
    this.items.push(item);
    this.total += price;
    console.log(
      `Added '${item}' ($${price.toFixed(2)}). Cart total: $${this.total.toFixed(2)}`,
    );
  }

  getItemCount(): number {
    return this.items.length;
  }

  isCheckedOut(): boolean {
    return this.checkedOut;
  }
}

// Each 'new' makes a new, empty cart; neither needs any arguments
const cart1 = new ShoppingCart();
const cart2 = new ShoppingCart();

cart1.addItem("Keyboard", 89.99);
cart1.addItem("Mouse", 29.99);

console.log(`Cart 1 items: ${cart1.getItemCount()}`);
console.log(`Cart 2 items: ${cart2.getItemCount()}`); // still empty: its own list
using System;
using System.Collections.Generic;
using static System.FormattableString;

// A shopping cart that starts empty: a default constructor
public class ShoppingCart
{
    private readonly List<string> _items;
    private double _total;

    public bool IsCheckedOut { get; private set; }

    // Default constructor: no parameters, every field gets its starting value
    public ShoppingCart()
    {
        _items = new List<string>(); // starts empty
        _total = 0.0;                // starts at zero
        IsCheckedOut = false;
    }

    public void AddItem(string item, double price)
    {
        _items.Add(item);
        _total += price;
        Console.WriteLine(
            Invariant($"Added '{item}' (${price:F2}). Cart total: ${_total:F2}"));
    }

    public int GetItemCount()
    {
        return _items.Count;
    }
}

public static class Program
{
    public static void Main()
    {
        // Each 'new' makes a new, empty cart; neither needs any arguments
        var cart1 = new ShoppingCart();
        var cart2 = new ShoppingCart();

        cart1.AddItem("Keyboard", 89.99);
        cart1.AddItem("Mouse", 29.99);

        Console.WriteLine($"Cart 1 items: {cart1.GetItemCount()}");
        // still empty: its own list
        Console.WriteLine($"Cart 2 items: {cart2.GetItemCount()}");
    }
}
package main

import "fmt"

// ShoppingCart starts empty: a default constructor
type ShoppingCart struct {
	items        []string
	total        float64
	isCheckedOut bool
}

// NewShoppingCart takes no parameters and gives every field its starting value.
// Go has no constructors, so a function does the job.
func NewShoppingCart() *ShoppingCart {
	return &ShoppingCart{
		items:        []string{}, // starts empty
		total:        0.0,        // starts at zero
		isCheckedOut: false,
	}
}

func (c *ShoppingCart) AddItem(item string, price float64) {
	c.items = append(c.items, item)
	c.total += price
	fmt.Printf("Added '%s' ($%.2f). Cart total: $%.2f\n", item, price, c.total)
}

func (c *ShoppingCart) ItemCount() int     { return len(c.items) }
func (c *ShoppingCart) IsCheckedOut() bool { return c.isCheckedOut }

func main() {
	// Each call makes a new, empty cart; neither needs any arguments
	cart1 := NewShoppingCart()
	cart2 := NewShoppingCart()

	cart1.AddItem("Keyboard", 89.99)
	cart1.AddItem("Mouse", 29.99)

	fmt.Printf("Cart 1 items: %d\n", cart1.ItemCount())
	fmt.Printf("Cart 2 items: %d\n", cart2.ItemCount()) // still empty: its own list
}

It prints:

Added 'Keyboard' ($89.99). Cart total: $89.99
Added 'Mouse' ($29.99). Cart total: $119.98
Cart 1 items: 2
Cart 2 items: 0

Both carts were made with no arguments, and each got its own empty list, so the second cart is still empty after the first one gets two items.

In Python, a class with no __init__ of its own still works: it uses the one every class inherits, which sets nothing. The object then has none of your attributes until something assigns them, and using one before that fails. A cart class without its __init__ stops at its first add_item with AttributeError: 'ShoppingCart' object has no attribute 'items'. Writing __init__ yourself, as here, makes sure every attribute exists from the start.

In Java, a class with no constructor gets one from the compiler. The Java tutorial says "The compiler automatically provides a no-argument, default constructor for any class without constructors." Its fields still start at Java's default values, as every field does; the language specification says "Each class variable, instance variable, or array component is initialized with a default value when it is created", which is 0 for numbers, false for booleans and null for objects. Once you write any constructor yourself, the compiler adds none, because, in the specification's words, "If a class contains no constructor declarations, then a default constructor is implicitly declared."

Parameterized Constructor: Custom Initial State

A parameterized constructor takes arguments, so each object starts with the values it is given. It is the kind you will write most, because most objects need some data to make sense: a user needs a name and an email, a bank account needs an owner. It is also the right place to check that data.

class User:
    """A user account that needs data to be made: a parameterized constructor."""

    def __init__(self, username: str, email: str, role: str = "member") -> None:
        # Validation: refuse bad data before the object exists
        if not username or not username.strip():
            raise ValueError("Username cannot be empty")
        if "@" not in email:
            raise ValueError(f"Invalid email: {email}")
        if role not in ("member", "admin", "moderator"):
            raise ValueError(f"Invalid role: {role}")

        self.username = username.strip()
        self.email = email.strip().lower()
        self.role = role          # "member" unless the caller gives another
        self.is_active = True     # every new user starts active

    def __repr__(self) -> str:
        return f"User('{self.username}', '{self.email}', role='{self.role}')"


alice = User("alice_dev", "alice@example.com")             # the default role
bob = User("bob_admin", "bob@example.com", role="admin")  # a role given

print(alice)
print(bob)

# The constructor refuses bad data, so an invalid User is never made
try:
    User("", "no-email")
except ValueError as e:
    print(f"Caught: {e}")
import java.util.Locale;

// A user account that needs specific data to be made: a parameterized constructor
public class User {
    private final String username;
    private final String email;
    private final String role;
    private final boolean isActive;

    // Parameterized constructor: refuses bad data before the object exists
    public User(String username, String email, String role) {
        if (username == null || username.trim().isEmpty()) {
            throw new IllegalArgumentException("Username cannot be empty");
        }
        if (email == null || !email.contains("@")) {
            throw new IllegalArgumentException("Invalid email: " + email);
        }
        if (!role.equals("member") && !role.equals("admin")
                && !role.equals("moderator")) {
            throw new IllegalArgumentException("Invalid role: " + role);
        }

        this.username = username.trim();
        this.email = email.trim().toLowerCase(Locale.ROOT);
        this.role = role;
        this.isActive = true; // every new user starts active
    }

    // A second constructor for the default role: it passes the work to the first
    public User(String username, String email) {
        this(username, email, "member");
    }

    public boolean isActive() {
        return isActive;
    }

    @Override
    public String toString() {
        return String.format("User('%s', '%s', role='%s')", username, email, role);
    }

    public static void main(String[] args) {
        User alice = new User("alice_dev", "alice@example.com"); // the default role
        User bob = new User("bob_admin", "bob@example.com", "admin"); // a role given

        System.out.println(alice);
        System.out.println(bob);

        // The constructor refuses bad data, so an invalid User is never made
        try {
            new User("", "no-email");
        } catch (IllegalArgumentException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <stdexcept>
#include <string>

namespace {
std::string trim(const std::string& s) {
    auto start = s.find_first_not_of(" \t\n");
    if (start == std::string::npos) return "";
    auto end = s.find_last_not_of(" \t\n");
    return s.substr(start, end - start + 1);
}

std::string lower(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
    return s;
}
}  // namespace

// A user account that needs specific data to be made: a parameterized constructor
class User {
public:
    // Parameterized constructor: refuses bad data before the object exists
    User(const std::string& username, const std::string& email, const std::string& role)
        : username_(trim(username)), email_(lower(trim(email))), role_(role),
          isActive_(true) {
        if (username_.empty()) {
            throw std::invalid_argument("Username cannot be empty");
        }
        if (email.find('@') == std::string::npos) {
            throw std::invalid_argument("Invalid email: " + email);
        }
        if (role != "member" && role != "admin" && role != "moderator") {
            throw std::invalid_argument("Invalid role: " + role);
        }
    }

    // A second constructor for the default role: it passes the work to the first
    User(const std::string& username, const std::string& email)
        : User(username, email, "member") {}

    bool isActive() const { return isActive_; }

    std::string toString() const {
        return "User('" + username_ + "', '" + email_ + "', role='" + role_ + "')";
    }

private:
    std::string username_;
    std::string email_;
    std::string role_;
    bool isActive_;  // every new user starts active
};

int main() {
    User alice("alice_dev", "alice@example.com");       // the default role
    User bob("bob_admin", "bob@example.com", "admin");  // a role given

    std::printf("%s\n", alice.toString().c_str());
    std::printf("%s\n", bob.toString().c_str());

    // The constructor refuses bad data, so an invalid User is never made
    try {
        User bad("", "no-email");
    } catch (const std::invalid_argument& e) {
        std::printf("Caught: %s\n", e.what());
    }
    return 0;
}
// A user account that needs specific data to be made: a parameterized constructor
class User {
  private readonly username: string;
  private readonly email: string;
  private readonly role: string;
  private readonly active: boolean;

  // Parameterized constructor: refuses bad data before the object exists.
  // TypeScript allows one constructor body, so a default value gives the second way.
  constructor(username: string, email: string, role: string = "member") {
    if (!username || !username.trim()) {
      throw new Error("Username cannot be empty");
    }
    if (!email.includes("@")) {
      throw new Error(`Invalid email: ${email}`);
    }
    if (!["member", "admin", "moderator"].includes(role)) {
      throw new Error(`Invalid role: ${role}`);
    }

    this.username = username.trim();
    this.email = email.trim().toLowerCase();
    this.role = role;
    this.active = true; // every new user starts active
  }

  isActive(): boolean {
    return this.active;
  }

  toString(): string {
    return `User('${this.username}', '${this.email}', role='${this.role}')`;
  }
}

const alice = new User("alice_dev", "alice@example.com"); // the default role
const bob = new User("bob_admin", "bob@example.com", "admin"); // a role given

console.log(alice.toString());
console.log(bob.toString());

// The constructor refuses bad data, so an invalid User is never made
try {
  new User("", "no-email");
} catch (e) {
  console.log(`Caught: ${(e as Error).message}`);
}
using System;

// A user account that needs specific data to be made: a parameterized constructor
public class User
{
    private readonly string _username;
    private readonly string _email;
    private readonly string _role;

    public bool IsActive { get; }

    // Parameterized constructor: refuses bad data before the object exists
    public User(string username, string email, string role)
    {
        if (string.IsNullOrWhiteSpace(username))
        {
            throw new ArgumentException("Username cannot be empty");
        }
        if (email == null || !email.Contains('@'))
        {
            throw new ArgumentException("Invalid email: " + email);
        }
        if (role != "member" && role != "admin" && role != "moderator")
        {
            throw new ArgumentException("Invalid role: " + role);
        }

        _username = username.Trim();
        _email = email.Trim().ToLowerInvariant();
        _role = role;
        IsActive = true; // every new user starts active
    }

    // A second constructor for the default role: it passes the work to the first
    public User(string username, string email) : this(username, email, "member")
    {
    }

    public override string ToString()
    {
        return $"User('{_username}', '{_email}', role='{_role}')";
    }
}

public static class Program
{
    public static void Main()
    {
        var alice = new User("alice_dev", "alice@example.com");      // the default role
        var bob = new User("bob_admin", "bob@example.com", "admin"); // a role given

        Console.WriteLine(alice);
        Console.WriteLine(bob);

        // The constructor refuses bad data, so an invalid User is never made
        try
        {
            _ = new User("", "no-email");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine("Caught: " + e.Message);
        }
    }
}
package main

import (
	"errors"
	"fmt"
	"strings"
)

// User needs specific data to be made: a parameterized constructor
type User struct {
	username string
	email    string
	role     string
	isActive bool
}

// NewUser refuses bad data before the user exists. Go has no constructors and no
// default arguments, so this function does the job and every caller passes a role.
func NewUser(username, email, role string) (*User, error) {
	if strings.TrimSpace(username) == "" {
		return nil, errors.New("Username cannot be empty")
	}
	if !strings.Contains(email, "@") {
		return nil, fmt.Errorf("Invalid email: %s", email)
	}
	if role != "member" && role != "admin" && role != "moderator" {
		return nil, fmt.Errorf("Invalid role: %s", role)
	}
	return &User{
		username: strings.TrimSpace(username),
		email:    strings.ToLower(strings.TrimSpace(email)),
		role:     role,
		isActive: true, // every new user starts active
	}, nil
}

func (u *User) IsActive() bool { return u.isActive }

func (u *User) String() string {
	return fmt.Sprintf("User('%s', '%s', role='%s')", u.username, u.email, u.role)
}

func main() {
	alice, _ := NewUser("alice_dev", "alice@example.com", "member") // the default role
	bob, _ := NewUser("bob_admin", "bob@example.com", "admin")      // a role given

	fmt.Println(alice)
	fmt.Println(bob)

	// The function refuses bad data, so an invalid User is never made
	if _, err := NewUser("", "no-email", "member"); err != nil {
		fmt.Println("Caught: " + err.Error())
	}
}

It prints:

User('alice_dev', 'alice@example.com', role='member')
User('bob_admin', 'bob@example.com', role='admin')
Caught: Username cannot be empty

Alice's account takes the default role, member, and Bob's is given admin. The third call never makes a user at all: the constructor finds the empty username and refuses before the object exists. That is the point of checking in the constructor. An empty username or an email without an @ is stopped at the door, so no other code ever meets a User in that state, and Encapsulation — Data Hiding Done Right takes the same care further.

Java gives the default role with a second constructor that hands its work to the first, this(username, email, "member"); Python gets the same from a default value for role. Further down, the ways to make an object in more than one way are compared across all six languages.

Copy Constructor: Cloning an Object

A copy constructor makes a new object from an existing one, with the same state. The new object is separate: changing one afterwards leaves the other as it was. Use one when you need a snapshot of an object as it is now: for undo, for a saved game, for a test that must not touch the original, or to make a variation without changing the original. A photocopy is the everyday version: the copy reads the same, but writing on it leaves the original clean.

Java and C# write it as a constructor that takes an object of its own class, and in C++ the copy constructor is part of the language. Python, TypeScript and Go have no such constructor, so each listing shows that language's own way, named in a comment: a class method in Python, a static method in TypeScript, a Copy method in Go.

class GameCharacter:
    """A game character that can be copied: a copy constructor."""

    def __init__(self, name: str, health: int, level: int,
                 inventory: list[str] | None = None) -> None:
        self.name = name
        self.health = health
        self.level = level
        # A new list, not the caller's own: the two can never change each other
        self.inventory = list(inventory) if inventory else []

    @classmethod
    def copy(cls, other: "GameCharacter") -> "GameCharacter":
        # Python has one __init__, so a class method plays the copy constructor
        return cls(other.name, other.health, other.level, list(other.inventory))

    def take_damage(self, amount: int) -> None:
        self.health = max(0, self.health - amount)

    def pick_up(self, item: str) -> None:
        self.inventory.append(item)

    def __repr__(self) -> str:
        return (f"GameCharacter('{self.name}', hp={self.health}, "
                f"lv={self.level}, items=[{', '.join(self.inventory)}])")


hero = GameCharacter("Aria", 100, 5, ["Sword", "Shield"])
print(f"Original: {hero}")

saved_state = GameCharacter.copy(hero)  # a snapshot: a new, separate character

hero.take_damage(40)
hero.pick_up("Potion")

print(f"After battle: {hero}")
print(f"Saved state:  {saved_state}")  # unchanged: it has its own list
import java.util.ArrayList;
import java.util.List;

// A game character that can be copied: a copy constructor
public class GameCharacter {
    private final String name;
    private int health;
    private final int level;
    private final List<String> inventory;

    public GameCharacter(String name, int health, int level, List<String> inventory) {
        this.name = name;
        this.health = health;
        this.level = level;
        // A new list, not the caller's own: the two can never change each other
        this.inventory = new ArrayList<>(inventory);
    }

    // Copy constructor: makes a new character from an existing one
    public GameCharacter(GameCharacter other) {
        this.name = other.name;
        this.health = other.health;
        this.level = other.level;
        this.inventory = new ArrayList<>(other.inventory); // its own list
    }

    public void takeDamage(int amount) {
        this.health = Math.max(0, this.health - amount);
    }

    public void pickUp(String item) {
        this.inventory.add(item);
    }

    @Override
    public String toString() {
        return String.format("GameCharacter('%s', hp=%d, lv=%d, items=[%s])",
                name, health, level, String.join(", ", inventory));
    }

    public static void main(String[] args) {
        GameCharacter hero = new GameCharacter("Aria", 100, 5,
                List.of("Sword", "Shield"));
        System.out.println("Original: " + hero);

        // a snapshot: a new, separate character
        GameCharacter savedState = new GameCharacter(hero);

        hero.takeDamage(40);
        hero.pickUp("Potion");

        System.out.println("After battle: " + hero);
        // unchanged: it has its own list
        System.out.println("Saved state:  " + savedState);
    }
}
#include <algorithm>
#include <cstdio>
#include <string>
#include <utility>
#include <vector>

// A game character that can be copied: a copy constructor
class GameCharacter {
public:
    GameCharacter(std::string name, int health, int level,
                  std::vector<std::string> inventory)
        : name_(std::move(name)), health_(health), level_(level),
          inventory_(std::move(inventory)) {}

    // Copy constructor: makes a new character from an existing one. Copying a
    // std::vector copies its items, so the new character has its own list.
    GameCharacter(const GameCharacter& other)
        : name_(other.name_), health_(other.health_), level_(other.level_),
          inventory_(other.inventory_) {}

    void takeDamage(int amount) { health_ = std::max(0, health_ - amount); }

    void pickUp(const std::string& item) { inventory_.push_back(item); }

    std::string toString() const {
        std::string items;
        for (std::size_t i = 0; i < inventory_.size(); ++i) {
            items += (i ? ", " : "") + inventory_[i];
        }
        return "GameCharacter('" + name_ + "', hp=" + std::to_string(health_) +
               ", lv=" + std::to_string(level_) + ", items=[" + items + "])";
    }

private:
    std::string name_;
    int health_;
    int level_;
    std::vector<std::string> inventory_;
};

int main() {
    GameCharacter hero("Aria", 100, 5, {"Sword", "Shield"});
    std::printf("Original: %s\n", hero.toString().c_str());

    GameCharacter savedState(hero);  // a snapshot: a new, separate character

    hero.takeDamage(40);
    hero.pickUp("Potion");

    std::printf("After battle: %s\n", hero.toString().c_str());
    // unchanged: it has its own list
    std::printf("Saved state:  %s\n", savedState.toString().c_str());
    return 0;
}
// A game character that can be copied: a copy constructor
class GameCharacter {
  private readonly name: string;
  private health: number;
  private readonly level: number;
  private readonly inventory: string[];

  constructor(name: string, health: number, level: number, inventory: string[] = []) {
    this.name = name;
    this.health = health;
    this.level = level;
    // A new list, not the caller's own: the two can never change each other
    this.inventory = [...inventory];
  }

  // TypeScript has one constructor, so a static method plays the copy constructor
  static copyOf(other: GameCharacter): GameCharacter {
    return new GameCharacter(other.name, other.health, other.level, [
      ...other.inventory,
    ]);
  }

  takeDamage(amount: number): void {
    this.health = Math.max(0, this.health - amount);
  }

  pickUp(item: string): void {
    this.inventory.push(item);
  }

  toString(): string {
    const items = this.inventory.join(", ");
    return (
      `GameCharacter('${this.name}', hp=${this.health}, ` +
      `lv=${this.level}, items=[${items}])`
    );
  }
}

const hero = new GameCharacter("Aria", 100, 5, ["Sword", "Shield"]);
console.log(`Original: ${hero.toString()}`);

const savedState = GameCharacter.copyOf(hero); // a snapshot: a new, separate character

hero.takeDamage(40);
hero.pickUp("Potion");

console.log(`After battle: ${hero.toString()}`);
console.log(`Saved state:  ${savedState.toString()}`); // unchanged: it has its own list
using System;
using System.Collections.Generic;

// A game character that can be copied: a copy constructor
public class GameCharacter
{
    private readonly string _name;
    private int _health;
    private readonly int _level;
    private readonly List<string> _inventory;

    public GameCharacter(string name, int health, int level, List<string> inventory)
    {
        _name = name;
        _health = health;
        _level = level;
        // A new list, not the caller's own: the two can never change each other
        _inventory = new List<string>(inventory);
    }

    // Copy constructor: makes a new character from an existing one
    public GameCharacter(GameCharacter other)
    {
        _name = other._name;
        _health = other._health;
        _level = other._level;
        _inventory = new List<string>(other._inventory); // its own list
    }

    public void TakeDamage(int amount)
    {
        _health = Math.Max(0, _health - amount);
    }

    public void PickUp(string item)
    {
        _inventory.Add(item);
    }

    public override string ToString()
    {
        return $"GameCharacter('{_name}', hp={_health}, lv={_level}, "
            + $"items=[{string.Join(", ", _inventory)}])";
    }
}

public static class Program
{
    public static void Main()
    {
        var hero = new GameCharacter("Aria", 100, 5,
            new List<string> { "Sword", "Shield" });
        Console.WriteLine("Original: " + hero);

        // a snapshot: a new, separate character
        var savedState = new GameCharacter(hero);

        hero.TakeDamage(40);
        hero.PickUp("Potion");

        Console.WriteLine("After battle: " + hero);
        // unchanged: it has its own list
        Console.WriteLine("Saved state:  " + savedState);
    }
}
package main

import (
	"fmt"
	"strings"
)

// GameCharacter can be copied: a copy constructor
type GameCharacter struct {
	name      string
	health    int
	level     int
	inventory []string
}

// NewGameCharacter makes a character; Go has no constructors, so a function does it
func NewGameCharacter(name string, health, level int,
	inventory []string) *GameCharacter {
	// A new slice, not the caller's own: the two can never change each other
	return &GameCharacter{name: name, health: health, level: level,
		inventory: append([]string(nil), inventory...)}
}

// Copy makes a new character from this one, with its own slice: Go's way to copy
func (c *GameCharacter) Copy() *GameCharacter {
	return NewGameCharacter(c.name, c.health, c.level, c.inventory)
}

func (c *GameCharacter) TakeDamage(amount int) {
	c.health = max(0, c.health-amount)
}

func (c *GameCharacter) PickUp(item string) {
	c.inventory = append(c.inventory, item)
}

func (c *GameCharacter) String() string {
	return fmt.Sprintf("GameCharacter('%s', hp=%d, lv=%d, items=[%s])",
		c.name, c.health, c.level, strings.Join(c.inventory, ", "))
}

func main() {
	hero := NewGameCharacter("Aria", 100, 5, []string{"Sword", "Shield"})
	fmt.Println("Original: " + hero.String())

	savedState := hero.Copy() // a snapshot: a new, separate character

	hero.TakeDamage(40)
	hero.PickUp("Potion")

	fmt.Println("After battle: " + hero.String())
	fmt.Println("Saved state:  " + savedState.String()) // unchanged: it has its own slice
}

It prints:

Original: GameCharacter('Aria', hp=100, lv=5, items=[Sword, Shield])
After battle: GameCharacter('Aria', hp=60, lv=5, items=[Sword, Shield, Potion])
Saved state:  GameCharacter('Aria', hp=100, lv=5, items=[Sword, Shield])

The hero takes 40 damage and picks up a Potion, and the snapshot still has 100 health and its two items.

The trap: sharing the list. Look at how the constructor stores the inventory: list(inventory) in Python, new ArrayList<>(inventory) in Java. Each makes a new list holding the same items. Had the copy been given the hero's own list, with self.inventory = other.inventory, the two objects would hold one list between them, and the Potion the hero picks up would show up in the snapshot too. A small lab ran the listing that way, and the snapshot printed GameCharacter('Aria', hp=100, lv=5, items=[Sword, Shield, Potion]): its health was still its own, but its items were not.

Python's documentation draws the line between two kinds of copy. "A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original." "A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original." Giving the copy a list of its own copies one level more than a shallow copy does. The items themselves are still shared, which does no harm here because the program never changes an item, only the lists; if the items were objects that can change, they would need copying too, all the way down, which is what a deep copy does.

The rule to keep: when an attribute holds something that can change, such as a list, a map or a set, give the copy its own. The same question comes back in Prototype Pattern, a design pattern built around copying objects.

Watch a Copy Share or Keep

Here is the same hero in memory, with each list drawn as an object of its own and each object's inventory as an arrow to a list. Choose "Share it" or "Copy it" for the copy's list, press "Save a snapshot", then "Take 40 damage" and "Pick up the Potion", and watch what the snapshot keeps.

The copy's health is always its own. Its list is the hero's own list when shared, so the Potion shows in both, and a list of its own when copied, so the snapshot keeps its two items.

Several Ways to Make an Object

Often a class should offer more than one way to make an object: with every value given, or with only the essentials and defaults for the rest. Each language has its own way of offering that, and this listing shows all six on one Rectangle.

class Rectangle:
    # Python allows one __init__, so default values give the three ways to call it
    def __init__(self, width: float = 1.0, height: float | None = None) -> None:
        self.width = width
        # one side given: a square
        self.height = height if height is not None else width

    def __repr__(self) -> str:
        return f"{self.width:.1f} x {self.height:.1f}"


print(Rectangle(10.0, 5.0))  # both sides
print(Rectangle(7.0))        # a square
print(Rectangle())           # the default 1 x 1
import java.util.Locale;

public class Rectangle {
    private final double width;
    private final double height;

    // Constructor 1: both sides given
    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    // Constructor 2: one side, a square; it passes the work to constructor 1
    public Rectangle(double side) {
        this(side, side);
    }

    // Constructor 3: no arguments, the default 1 x 1; also passed to constructor 1
    public Rectangle() {
        this(1.0, 1.0);
    }

    @Override
    public String toString() {
        return String.format(Locale.ROOT, "%.1f x %.1f", width, height);
    }

    public static void main(String[] args) {
        System.out.println(new Rectangle(10.0, 5.0)); // both sides
        System.out.println(new Rectangle(7.0));       // a square
        System.out.println(new Rectangle());          // the default 1 x 1
    }
}
#include <cstdio>
#include <string>

class Rectangle {
public:
    // Constructor 1: both sides given
    Rectangle(double width, double height) : width_(width), height_(height) {}

    // Constructor 2: one side, a square; it passes the work to constructor 1
    explicit Rectangle(double side) : Rectangle(side, side) {}

    // Constructor 3: no arguments, the default 1 x 1; also passed to constructor 1
    Rectangle() : Rectangle(1.0, 1.0) {}

    std::string toString() const {
        char text[48];
        std::snprintf(text, sizeof text, "%.1f x %.1f", width_, height_);
        return text;
    }

private:
    double width_;
    double height_;
};

int main() {
    std::printf("%s\n", Rectangle(10.0, 5.0).toString().c_str());  // both sides
    std::printf("%s\n", Rectangle(7.0).toString().c_str());        // a square
    std::printf("%s\n", Rectangle().toString().c_str());           // the default 1 x 1
    return 0;
}
class Rectangle {
  private readonly width: number;
  private readonly height: number;

  // TypeScript lists the three ways to call it as overloads over one constructor body
  constructor();
  constructor(side: number);
  constructor(width: number, height: number);
  constructor(width: number = 1.0, height?: number) {
    this.width = width;
    this.height = height ?? width; // one side given: a square
  }

  toString(): string {
    return `${this.width.toFixed(1)} x ${this.height.toFixed(1)}`;
  }
}

console.log(new Rectangle(10.0, 5.0).toString()); // both sides
console.log(new Rectangle(7.0).toString()); // a square
console.log(new Rectangle().toString()); // the default 1 x 1
using System;
using static System.FormattableString;

public class Rectangle
{
    private readonly double _width;
    private readonly double _height;

    // Constructor 1: both sides given
    public Rectangle(double width, double height)
    {
        _width = width;
        _height = height;
    }

    // Constructor 2: one side, a square; it passes the work to constructor 1
    public Rectangle(double side) : this(side, side)
    {
    }

    // Constructor 3: no arguments, the default 1 x 1; also passed to constructor 1
    public Rectangle() : this(1.0, 1.0)
    {
    }

    public override string ToString()
    {
        return Invariant($"{_width:F1} x {_height:F1}");
    }
}

public static class Program
{
    public static void Main()
    {
        Console.WriteLine(new Rectangle(10.0, 5.0)); // both sides
        Console.WriteLine(new Rectangle(7.0));       // a square
        Console.WriteLine(new Rectangle());          // the default 1 x 1
    }
}
package main

import "fmt"

type Rectangle struct {
	width  float64
	height float64
}

// Go has no constructors and no overloading: each way of making one is a function
// with its own name, and the two shorter ones pass the work to NewRectangle.

// NewRectangle makes a rectangle with both sides given
func NewRectangle(width, height float64) *Rectangle {
	return &Rectangle{width: width, height: height}
}

// NewSquare makes one from a single side
func NewSquare(side float64) *Rectangle { return NewRectangle(side, side) }

// NewDefaultRectangle makes the default 1 x 1
func NewDefaultRectangle() *Rectangle { return NewRectangle(1.0, 1.0) }

func (r *Rectangle) String() string {
	return fmt.Sprintf("%.1f x %.1f", r.width, r.height)
}

func main() {
	fmt.Println(NewRectangle(10.0, 5.0)) // both sides
	fmt.Println(NewSquare(7.0))          // a square
	fmt.Println(NewDefaultRectangle())   // the default 1 x 1
}

It prints:

10.0 x 5.0
7.0 x 7.0
1.0 x 1.0

Java, C++ and C# let a class have several constructors with different parameter lists and pick the one that matches the arguments. This is called constructor overloading. Here the two shorter constructors hand their work to the full one, so the setting up is written once; the Java tutorial calls this "an explicit constructor invocation". Writing this(side, side) in Java and C#, or : Rectangle(side, side) in C++, does it.

Python allows one __init__ per class, so default values do the job. Python's own FAQ says "In Python you have to write a single constructor that catches all cases using default arguments." For a way of making objects that defaults cannot express, Python uses a class method as a named alternative constructor, as GameCharacter.copy does above.

TypeScript lists the ways to call a constructor as overload signatures above one constructor body.

Go has no constructors and no overloading, so each way is a function with its own name: NewRectangle, NewSquare and NewDefaultRectangle.

Common Mistakes

Mistake 1: no checks in the constructor. A constructor that accepts anything lets invalid objects into the program, and they fail later, far from where they were made:

class User:
    def __init__(self, email):
        self.email = email  # empty? not an email at all? nothing stops it

Check in the constructor instead, as User above does, so the problem shows at the moment the object is made.

Mistake 2: sharing a list you meant to copy. Storing the caller's list itself ties two objects together:

self.inventory = inventory  # the caller's own list: a change there shows here

Store a list of your own instead:

self.inventory = list(inventory)  # a new list with the same items

Mistake 3: doing too much in the constructor. Network calls and file reads inside a constructor make objects slow and unpredictable to create, and make the class hard to test, since no object can be made without them. Keep the constructor to setting up state, and do the rest in a method of its own:

user = User("alice_dev", "alice@example.com")  # quick and predictable
user.load_profile_from_api()                    # a separate step, easy to test

Key Takeaways

  • A constructor runs by itself as an object is made and gives it its starting state. In Java it carries the class's name, in Python it is __init__, and neither returns a value.
  • A default constructor takes no arguments and starts every attribute at a value it chooses. A parameterized one takes the values and is the place to check them, so an invalid object is never made.
  • A copy constructor makes a separate object with the same state. Give the copy its own copy of anything that can change, such as a list, or the two objects stay tied together.
  • More than one way to make an object comes from overloaded constructors in Java, C++ and C#, default values in Python, overload signatures in TypeScript and named functions in Go.
  • Encapsulation — Data Hiding Done Right comes next: keeping an object's data safe once it is made.