Skip to the page

Classes and objects · core

Constructors, destructors and their order

A constructor sets up an object and a destructor cleans it up. Bases are built first and destroyed last, and members follow the order in which they are declared.

The notes

What you must know

  • A constructor has the class name and no return type. The compiler writes a default constructor only when you declare no constructor at all; Student() = default; asks for it back.
  • The member initializer list, Student(int r) : roll(r) {}, sets members before the body runs. const members, reference members and bases without a default constructor must be set there.
  • Members are initialised in the order they are declared in the class, not in the order of the initializer list. g++ -Wall warns when the two orders differ (-Wreorder).
  • Construction order: the base class first, then the members in declaration order, then the constructor body. Destruction is the exact reverse: the destructor body, the members in reverse, then the base.
  • A destructor, ~Student(), has no parameters and no return type, and a class has only one. It runs at the end of the scope for a local, at delete for a heap object, and at program end for a global or static.
  • Local objects in one scope are destroyed in the reverse order of their creation.
  • Base* p = new Derived(); delete p; with a non-virtual ~Base is undefined behaviour; in practice often only ~Base runs, and the Derived cleanup is skipped. Fix: virtual ~Base().
  • A virtual function called inside a constructor or destructor runs that class's own version, not the derived one: the derived part does not exist yet, or no longer exists.

The red pen

Common traps: mistake → fix

  • Mistake: The derived constructor runs first

    Fix: the base constructor runs first.

  • Mistake: Members are set in the order of the initializer list

    Fix: they are set in declaration order.

  • Mistake: The compiler always gives a default constructor

    Fix: only when you declare no constructor.

  • Mistake: A destructor can be overloaded

    Fix: a class has exactly one destructor.

Easy to hard

Questions interviewers ask, easy to hard

  1. In what order do constructors and destructors run for Base and Derived?
  2. What does this program print? (Derived d;, then Base* p = new Derived(); delete p; with a non-virtual ~Base)
  3. Why do we need a virtual destructor?
  4. When must you use a member initializer list?
  5. When does the compiler write a default constructor for you?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview