Chapter 04 of 26

Constructors & Destructors

Every object has a life. It is born when it is created, it does its work, and at some point it dies and its memory is reused. Two moments in that life are special:

  • At birth, the object must be put into a valid starting state. A BankAccount without an owner, or a Rectangle with negative width, should never exist even for a moment.

  • At death, the object may need to release what it holds: close a file, return a database connection, free memory.

The first job is done by a constructor and the second by a destructor. In this chapter we will study both, and see how Java, C++ and Python handle them very differently. We build on the classes and objects from Classes & Objects.


What Is a Constructor?

A constructor is a special member of a class that is executed automatically when an object is created, and whose job is to initialise the new object.

In Java and C++, a constructor:

  • has exactly the same name as the class;

  • has no return type, not even void (if you write one, Java treats it as an ordinary method that merely shares the class name);

  • is called automatically when the object is created (with new in Java, or when a C++ object is defined);

  • can take parameters and can be overloaded;

  • is not inherited by subclasses.

In Java a constructor cannot be static, final, abstract or synchronized, but it can be public, protected, package-private or private. In C++ a constructor cannot be virtual.


Types of Constructors

Type

What it is

Example

Default (compiler-generated)

Added automatically by the compiler when the class declares no constructor at all

(invisible) Book() { }

No-argument (user-written)

A constructor you write that takes no parameters

Book() { title = "Untitled"; }

Parameterised

Takes arguments to set the initial state

Book(String title, double price)

Copy

Creates a new object as a copy of an existing one

Book(Book other) in Java, Book(const Book& other) in C++

Terminology trap: in Java, "default constructor" strictly means the one the compiler adds. In C++, a "default constructor" is any constructor that can be called with no arguments, whether you wrote it or the compiler generated it. Read exam questions with this in mind.

The default constructor disappears

Java (and C++) add the no-argument default constructor only if you declare no constructor at all. The moment you write any constructor, it is gone:

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }
}

class Main {
    public static void main(String[] args) {
        Student s = new Student();
    }
}
Main.java:11: error: constructor Student in class Student cannot be applied to given types;
        Student s = new Student();
                    ^
  required: String
  found:    no arguments
  reason: actual and formal argument lists differ in length
1 error

If you still want new Student() to work, you must write a no-argument constructor yourself.


Constructor Overloading and Chaining

A class can have several constructors with different parameter lists. To avoid repeating the same assignments in each of them, one constructor can call another using this(...). This is called constructor chaining.

class Book {
    String title;
    String author;
    double price;

    // 1. No-argument constructor
    Book() {
        this("Untitled", "Unknown");      // calls constructor 2
        System.out.println("  Book() finished");
    }

    // 2. Two-argument constructor
    Book(String title, String author) {
        this(title, author, 0.0);         // calls constructor 3
        System.out.println("  Book(title, author) finished");
    }

    // 3. Full constructor: the only place that really assigns fields
    Book(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
        System.out.println("  Book(title, author, price) finished");
    }

    // 4. Copy constructor (written by us; Java does not generate one)
    Book(Book other) {
        this(other.title, other.author, other.price);
        System.out.println("  Book(Book) finished");
    }

    void show() {
        System.out.println(title + " by " + author + ", Rs " + price);
    }
}

class Main {
    public static void main(String[] args) {
        System.out.println("b1:");
        Book b1 = new Book();
        System.out.println("b2:");
        Book b2 = new Book("Wings of Fire", "A. P. J. Abdul Kalam", 399);
        System.out.println("b3:");
        Book b3 = new Book(b2);

        b3.price = 299;                   // change the copy only
        b1.show();
        b2.show();
        b3.show();
    }
}

Output:

b1:
  Book(title, author, price) finished
  Book(title, author) finished
  Book() finished
b2:
  Book(title, author, price) finished
b3:
  Book(title, author, price) finished
  Book(Book) finished
Untitled by Unknown, Rs 0.0
Wings of Fire by A. P. J. Abdul Kalam, Rs 399.0
Wings of Fire by A. P. J. Abdul Kalam, Rs 299.0

Trace new Book(): constructor 1 immediately calls constructor 2, which calls constructor 3. Constructor 3 assigns the fields and finishes first; control then returns to 2, then to 1. That is why the messages appear in reverse order.

Why chain? Because all the real initialisation and validation now lives in one constructor. If we later add a check like "price cannot be negative", we add it in one place and every way of creating a Book gets it.

Rules for this(...) in Java:

  • It can only be used inside a constructor.

  • A constructor can call this(...) at most once, and cannot call both this(...) and super(...).

  • In Java 17 (and up to Java 24), this(...) or super(...) must be the first statement. From Java 25, "flexible constructor bodies" (JEP 513, previewed in Java 22–24) allow statements such as argument validation before it, as long as they do not read the object being built or call its methods (assigning its own fields is allowed).

  • Constructors must not call each other in a cycle; the compiler reports "recursive constructor invocation".

Copy constructor

Constructor 4, Book(Book other), builds a new book from an existing one. Changing b3.price did not affect b2, because b3 is a separate object. Java does not generate copy constructors automatically; you write them when you need them. (Java also has clone(), which is widely considered awkward; a copy constructor or a static factory is usually preferred.) Whether a copy shares inner objects or duplicates them is explained in Shallow Copy vs Deep Copy.


Order of Initialisation in Java

Besides the constructor, a Java class can initialise fields with field initialisers and instance initialiser blocks. When does each run?

class Demo {
    int a = initA();                      // field initializer

    {                                     // instance initializer block
        System.out.println("2. instance block, a = " + a);
    }

    Demo() {
        System.out.println("3. constructor body");
    }

    int initA() {
        System.out.println("1. field initializer");
        return 10;
    }
}

class Main {
    public static void main(String[] args) {
        new Demo();
    }
}

Output:

1. field initializer
2. instance block, a = 10
3. constructor body

When new Demo() runs:

  1. Memory is allocated and all fields get default values (a = 0).

  2. The superclass constructor runs (here, Object()).

  3. Field initialisers and instance initialiser blocks run, in the order they appear in the source.

  4. The rest of the constructor body runs.

Static fields and static blocks are different: they run once, when the class is first loaded, before any object is created. See Static vs Instance Members.


Private Constructors

A constructor can be private, which means code outside the class cannot use new on it. This sounds strange but is very useful:

  • Utility classes with only static methods (like java.lang.Math) have a private constructor so nobody creates pointless objects.

  • Static factory methods let the class control how objects are created. For example, java.time.LocalDate has no public constructor; you write LocalDate.of(2026, 11, 2) instead of new LocalDate(...).

  • The Singleton pattern uses a private constructor to guarantee only one instance; see Creational Patterns: Singleton, Factory & Builder.


Constructors and Destructors in C++

C++ gives us a clear view of the full object life cycle because it has real destructors.

A destructor is a special member function that is executed automatically when an object's lifetime ends, used to release resources the object owns.

Rules for a C++ destructor:

  • Its name is the class name with a tilde: ~Tracer().

  • It takes no parameters and has no return type, so it cannot be overloaded; a class has exactly one.

  • If you do not write one, the compiler generates one.

  • It runs automatically when a stack object goes out of scope, when delete is used on a heap object, or when the containing object is destroyed.

#include <iostream>
#include <string>

class Tracer {
    std::string name;
public:
    Tracer(std::string n) : name(std::move(n)) {          // constructor
        std::cout << "construct " << name << '\n';
    }
    Tracer(const Tracer& other) : name(other.name + "-copy") {  // copy constructor
        std::cout << "copy      " << name << '\n';
    }
    ~Tracer() {                                            // destructor
        std::cout << "destroy   " << name << '\n';
    }
};

void work() {
    Tracer t("local-in-work");
    std::cout << "  ...working...\n";
}   // t is destroyed here, automatically

int main() {
    Tracer a("A");
    Tracer b("B");
    Tracer c = a;                         // copy constructor runs

    work();

    {
        Tracer inner("inner");
    }                                     // inner destroyed at end of this block

    Tracer* h = new Tracer("heap");
    delete h;                             // heap object: destroyed only on delete

    std::cout << "end of main\n";
}                                         // c, b, a destroyed in reverse order

Output (g++ 15, -std=c++23):

construct A
construct B
copy      A-copy
construct local-in-work
  ...working...
destroy   local-in-work
construct inner
destroy   inner
construct heap
destroy   heap
end of main
destroy   A-copy
destroy   B
destroy   A

Read the output carefully, because it shows every rule:

  • Tracer c = a; calls the copy constructor, which C++ would have generated automatically if we had not written our own.

  • The local object inside work() is destroyed the moment work() returns.

  • inner is destroyed at the closing brace of its block.

  • The heap object is destroyed only when we call delete. Forget the delete and you get a memory leak, and its destructor never runs.

  • At the end of main, c, b, a are destroyed in reverse order of construction. Objects created later may depend on earlier ones, so they are cleaned up first.

Member initialiser list

Notice Tracer(std::string n) : name(std::move(n)) { ... }. The part after the colon is the member initialiser list. It initialises members directly instead of first default-constructing them and then assigning. It is required for const members, reference members and members without a default constructor, and is generally the preferred style.

RAII: the big idea behind destructors

RAII (Resource Acquisition Is Initialisation) is the most important C++ idiom: acquire a resource in the constructor and release it in the destructor. Because destructors run automatically, even when an exception is thrown, resources are never leaked. std::string, std::vector, std::unique_ptr, std::fstream and std::lock_guard all work this way.

Looking ahead: when a class is meant to be a base class and objects may be deleted through a base-class pointer, its destructor should be declared virtual. This will make sense after Inheritance and Polymorphism.


Does Java Have Destructors?

No. Java has no destructors. Objects are not destroyed at a predictable moment; the garbage collector reclaims memory some time after an object becomes unreachable (details in Object Lifecycle & Memory). For memory, that is great: no delete, no leaks of that kind, no dangling pointers.

But memory is not the only resource. Files, sockets and database connections must be closed promptly, and you cannot wait for the garbage collector.

What about finalize()?

Older books describe finalize() as "Java's destructor". Do not use it. It was deprecated in Java 9, and Java 18 deprecated finalization for removal (JEP 421). It may run late, or never, it slows down garbage collection, and its behaviour is hard to reason about.

The modern answer: AutoCloseable and try-with-resources

class Connection implements AutoCloseable {
    private final String name;

    Connection(String name) {
        this.name = name;
        System.out.println("open  " + name);
    }

    void send(String msg) {
        System.out.println("send  " + msg + " via " + name);
    }

    @Override
    public void close() {
        System.out.println("close " + name);
    }
}

class Main {
    public static void main(String[] args) {
        try (Connection db = new Connection("db");
             Connection cache = new Connection("cache")) {
            db.send("SELECT 1");
            cache.send("PING");
            throw new IllegalStateException("something failed");
        } catch (IllegalStateException e) {
            System.out.println("caught: " + e.getMessage());
        }
    }
}

Output:

open  db
open  cache
send  SELECT 1 via db
send  PING via cache
close cache
close db
caught: something failed
  • Any class that implements AutoCloseable (or Closeable) can be used in a try (...) header.

  • close() is called automatically when the block ends, whether normally or because of an exception, before the catch block runs.

  • Resources are closed in reverse order of opening (cache before db), just like C++ destructors.

For a rare safety net (cleaning up if the programmer forgot to call close()), Java offers java.lang.ref.Cleaner, but explicit close() with try-with-resources should always be the main mechanism.


Constructors and Destructors in Python

Python's __init__ is commonly called the constructor, although technically the object is created by __new__ and __init__ only initialises it. Python also has __del__, which is called just before an object is reclaimed.

class Tracer:
    def __init__(self, name):
        self.name = name
        print("init", name)

    def __del__(self):
        print("del ", self.name)


a = Tracer("A")
b = a                 # second reference to the same object
del a                 # removes a name, NOT the object
print("after del a")
b = None              # last reference gone
print("after b = None")

Output (CPython 3.14):

init A
after del a
del  A
after b = None
  • del a deletes the name a, not the object. The object is still referenced by b.

  • CPython uses reference counting, so __del__ ran as soon as the last reference disappeared. That is an implementation detail: objects in reference cycles are freed later by the cycle collector, and __del__ is not guaranteed to run for objects still alive when the interpreter exits.

  • For dependable cleanup, Python uses context managers with the with statement (with open("data.txt") as f:), the equivalent of Java's try-with-resources.


Comparison Tables

Constructor vs Destructor

Constructor

Destructor

Initialises an object when it is created

Releases resources when the object's lifetime ends

Same name as the class

Class name with ~ prefix (C++)

Can take parameters

Takes no parameters

Can be overloaded (many per class)

Cannot be overloaded (one per class)

Cannot be virtual (C++)

Can be, and often should be, virtual in a base class (C++)

Called in order of construction

Called in reverse order of construction

Java vs C++ vs Python

Feature

Java

C++

Python

Constructor

ClassName(...)

ClassName(...)

__init__(self, ...)

Constructor overloading

Yes

Yes

No (use default arguments or @classmethod factories)

Copy constructor

Only if you write it

Generated automatically if not written (unless the class declares a move constructor or move assignment)

No; use copy.copy / copy.deepcopy

Destructor

None

~ClassName(), deterministic

__del__, not reliable for cleanup

Memory freed by

Garbage collector

Scope end / delete / smart pointers

Reference counting + cycle collector (CPython)

Deterministic cleanup tool

try-with-resources + AutoCloseable

RAII (destructors)

with + context managers


Common Mistakes Students Make

  • Writing a return type on a constructor. void Book() { } compiles in Java, but it is a normal method, not a constructor, so it never runs on new Book().

  • Expecting the default constructor after writing a parameterised one. Once any constructor exists, the compiler stops adding the no-argument one.

  • Calling this(...) after other statements in Java 17. It must be the first statement (Java 25 relaxes this only partially).

  • Calling finalize() a destructor or relying on it. Use try-with-resources.

  • Forgetting delete for objects made with new in C++ (or better, not using raw new at all; prefer stack objects and smart pointers).

  • Calling an overridable method from a constructor. A subclass version could run before the subclass's fields are set. Keep constructors simple.


Interview / GATE-Style Questions

1. Can a constructor return a value?

No. A constructor has no return type. You may write a bare return; to exit early, but you cannot return a value. The result of new is the reference to the newly created object, supplied by the language, not by the constructor.

2. Can a constructor be private? Why would you do that?

Yes. To stop outside code from creating objects directly: utility classes with only static methods, classes created through static factory methods, and the Singleton pattern.

3. Why can't a destructor be overloaded in C++?

Overloading needs different parameter lists, but a destructor takes no parameters, so only one signature is possible. Also, the destructor is called automatically by the language, which would have no way to choose between versions.

4. In what order are destructors called for A a; B b; C c; declared in that order in a function?

Reverse order of construction: ~C, then ~B, then ~A.

5. Does Java support destructors? How do you release resources?

No. Memory is reclaimed by the garbage collector. Other resources are released by implementing AutoCloseable and using try-with-resources, which calls close() automatically, in reverse order of opening, even if an exception occurs. finalize() is deprecated for removal.

6. What is the output order when new Demo() runs for a class with a field initialiser, an instance block and a constructor?

Superclass constructor first, then field initialisers and instance blocks in textual order, then the remaining constructor body.

7. When is a copy constructor called in C++?

When a new object is initialised from an existing object of the same type: T b = a; or T b(a);, when an object is passed by value to a function, and when a local object is returned by value and the class has no move constructor (compilers usually elide that copy anyway, and since C++17 the copy is guaranteed to be elided when returning a temporary such as return T(5);).

8. What is the difference between __init__ and a constructor in Java?

__init__ initialises an object that __new__ has already created; a Java constructor runs after new has allocated the object, so the roles are similar. The main practical differences: Python cannot overload __init__, and fields are created inside it by assignment rather than declared in the class.


Summary

  • A constructor initialises a new object; it has the class's name, no return type, runs automatically and can be overloaded.

  • Types: compiler-generated default, user-written no-argument, parameterised and copy constructors. The default disappears once you write any constructor.

  • this(...) chains constructors so validation lives in one place.

  • Java initialisation order: defaults → superclass constructor → field initialisers and instance blocks in order → constructor body.

  • A C++ destructor (~Name()) runs automatically at end of lifetime, in reverse order of construction, and is the basis of RAII.

  • Java has no destructors; use AutoCloseable with try-with-resources. Python's __del__ exists but use with for reliable cleanup.

Next, in Encapsulation, we will use constructors and private fields together to make objects that can never be put into an invalid state.