SyntaxPilot
Courses/C++/Lesson 13
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ · Lesson 13 of 40

Constructors and destructors

queued

These are the notes for C++ episode 13. Episode 12 ended with an account that printed garbage because we forgot to call open(). Here you will invent the constructor (setup that runs by itself, so it can't be forgotten), overloaded and default constructors, the member initializer list (needed for const members), the destructor (cleanup that runs by itself) and the order objects are destroyed in. Then a class that owns heap memory: without a destructor it leaks, and when you copy it, it crashes with double free detected, until you write a copy constructor that makes a deep copy. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.

The problem: an object that was never set up

#include <iostream>
#include <string>
using namespace std;

class Account {
    string owner;
    double balance;
public:
    void open(string n, double b) { owner = n; balance = b; }
    void show() { cout << owner << ": " << balance << endl; }
};

int main() {
    Account c;
    c.show();
    return 0;
}

One run printed:

: 6.95259e-310

An empty name and a garbage balance (it changes from run to run).

Why it failed: creating the object and setting it up are two separate steps, and the second one is just a function we have to remember to call. Setup you can forget will be forgotten.

The fix: a constructor (hotel check-in)

A hotel never gives you a room and says "please remember to check in later". Check-in happens the moment you arrive, and without your ID there's no key.

At a hotel In C++
Check-in happens on arrival a constructor runs automatically when the object is created
No ID, no room key a constructor with parameters: no data, no object
The room is ready from minute one the object is correct from the start
#include <iostream>
#include <string>
using namespace std;

class Account {
    string owner;
    double balance;
public:
    Account(string n, double b) {
        owner = n;
        balance = b;
        cout << "Opened: " << owner << endl;
    }
    void show() { cout << owner << ": " << balance << endl; }
};

int main() {
    Account a("Ravi", 5000);
    a.show();
    return 0;
}

Output:

Opened: Ravi
Ravi: 5000
  • A constructor has the same name as the class and no return type, not even void.
  • The data goes in round brackets when the object is created: Account a("Ravi", 5000);. (Curly braces work too: Account a{"Ravi", 5000};.)
  • We never called it; it ran by itself when a was created.

Now the old mistake, Account c; with no details:

main.cpp:19:13: error: no matching function for call to 'Account::Account()'

The only constructor needs a name and a balance, so an account without them can't be built. The garbage bug became a compile error.

More than one constructor

Sometimes you do want an account with no details: a guest account starting at 0. Constructors can be overloaded (episode 7) like any function:

#include <iostream>
#include <string>
using namespace std;

class Account {
    string owner;
    double balance;
public:
    Account(string n, double b) {
        owner = n;
        balance = b;
        cout << "Opened: " << owner << endl;
    }
    Account() { owner = "Guest"; balance = 0; }
    void show() { cout << owner << ": " << balance << endl; }
};

int main() {
    Account a("Ravi", 5000);
    Account g;
    a.show();
    g.show();
    return 0;
}

Output:

Opened: Ravi
Ravi: 5000
Guest: 0

C++ picks the constructor whose parameters match. A constructor with no parameters is called the default constructor.

Constructor rules

  1. Same name as the class, no return type. Writing void Account(string n, double b) gives error: return type specification for constructor invalid.
  2. Runs automatically when the object is created.
  3. Can be overloaded, as long as the parameter lists differ.
  4. If you write no constructor at all, C++ quietly gives you an empty default one. That's why Account c; compiled in episode 12.
  5. The moment you write any constructor, that free default one disappears.
  6. Watch out: Account a(); with empty brackets does not create an object. C++ reads it as the declaration of a function named a that returns an Account (the "most vexing parse"). g++ warns empty parentheses were disambiguated as a function declaration, and then a.show(); fails with request for member 'show' in 'a', which is of non-class type 'Account()'. Write Account a; or Account a{};.

The member initializer list (printed on the passbook)

A real account has an account number. It's printed on the passbook when the account is opened and never changes. In C++, a member that must never change is a const member. The obvious attempt sets it in the constructor body:

#include <iostream>
#include <string>
using namespace std;

class Account {
    const int accNo;
    string owner;
    double balance;
public:
    Account(int no, string n, double b) {
        accNo = no; owner = n; balance = b;
    }
    void show() { cout << accNo << " " << owner << endl; }
};

int main() {
    Account a(1001, "Ravi", 5000);
    a.show();
    return 0;
}

g++ says:

main.cpp:10:5: error: uninitialized const member in 'const int' [-fpermissive]
main.cpp:11:15: error: assignment of read-only member 'Account::accNo'

Why: by the time the constructor's body runs, every member already exists. A const that already exists can't be assigned. It's too late for the pen; it had to be printed while the passbook was made.

The fix: after the constructor's brackets, a colon and a list of member(value). This is the member initializer list: it sets each member while it is being created, before the body starts.

#include <iostream>
#include <string>
using namespace std;

class Account {
    const int accNo;
    string owner;
    double balance;
public:
    Account(int no, string n, double b)
        : accNo(no), owner(n), balance(b) {}
    void show() { cout << accNo << " " << owner << endl; }
};

int main() {
    Account a(1001, "Ravi", 5000);
    a.show();
    return 0;
}

Output:

1001 Ravi
  • const members and reference members must be set in the initializer list.
  • For every other member it's the preferred style: the member is built with the right value once, instead of being built and then overwritten.
  • Members are initialised in the order they are declared in the class, not the order you list them, so keep the two orders the same.
  • The body {} can be empty.

Destructors (hotel check-out)

Check-in has a partner: check-out. Return the key, clean the room. In C++, cleanup that runs automatically when an object dies is a destructor. Its name is the class name with a tilde (~) in front. It has no return type and no parameters (~Account(int x) gives error: destructors may not have parameters), so there's exactly one per class.

An object dies when its scope ends: at the closing brace of the block it was created in. Objects are destroyed in reverse order of creation, like a stack of plates: the last one placed is the first one taken.

#include <iostream>
#include <string>
using namespace std;

class Account {
    string owner;
public:
    Account(string n) { owner = n; cout << "Opened: " << owner << endl; }
    ~Account() { cout << "Closed: " << owner << endl; }
};

int main() {
    Account a("Ravi");
    Account b("Priya");
    {
        Account t("Temp");
        cout << "-- end of block --" << endl;
    }
    cout << "-- end of main --" << endl;
    return 0;
}

Output:

Opened: Ravi
Opened: Priya
Opened: Temp
-- end of block --
Closed: Temp
-- end of main --
Closed: Priya
Closed: Ravi

Temp dies at the end of its own block; Ravi and Priya die at the end of main, in reverse order. We never called the destructor.

Why destructors matter: objects that own memory

Printing messages is nice, but the real job of a destructor is giving back what the object took. In episode 10 we rented heap memory with new. Now a class does it in its constructor:

#include <iostream>
#include <string>
using namespace std;

class MarkList {
    int n; int* data;
public:
    MarkList(int count) : n(count), data(new int[count]{}) {
        cout << "Rented " << n << " slots" << endl;
    }
};

int main() {
    for (int i = 1; i <= 3; i++) {
        MarkList m(i * 100);
    }
    return 0;
}

Output:

Rented 100 slots
Rented 200 slots
Rented 300 slots

new int[count]{} rents count ints and the empty {} fills them with zeros. Each MarkList dies at the end of its loop round, but dying doesn't return the memory: 600 ints rented, none returned. That's a memory leak, and in a program that runs for days, a loop like this would eventually eat all the memory.

Add the destructor:

#include <iostream>
#include <string>
using namespace std;

class MarkList {
    int n; int* data;
public:
    MarkList(int count) : n(count), data(new int[count]{}) {
        cout << "Rented " << n << " slots" << endl;
    }
    ~MarkList() { delete[] data; cout << "Returned " << n << endl; }
};

int main() {
    for (int i = 1; i <= 3; i++) {
        MarkList m(i * 100);
    }
    return 0;
}

Output:

Rented 100 slots
Returned 100
Rented 200 slots
Returned 200
Rented 300 slots
Returned 300

Every block of memory goes back the moment its object dies, and main never wrote delete. Rent in the constructor, return in the destructor. This idea has a famous name: RAII (Resource Acquisition Is Initialization): tie a resource (memory, a file, a lock) to an object's lifetime.

The copy crash: two keys, one godown

Copying a MarkList (MarkList b = a;) copies each member, including the pointer. That's like photocopying a godown key: two keys, still one godown.

#include <iostream>
#include <string>
using namespace std;

class MarkList {
    int n; int* data;
public:
    MarkList(int count) : n(count), data(new int[count]{}) {
        cout << "Rented " << n << " slots" << endl;
    }
    ~MarkList() { delete[] data; cout << "Returned " << n << endl; }
};

int main() {
    MarkList a(5);
    MarkList b = a;
    return 0;
}

What happened:

Rented 5 slots
Returned 5
free(): double free detected in tcache 2

and the program was aborted (it crashed). b died first and deleted the array; then a died and deleted the same array again. That's a double free. Copying only the pointer is called a shallow copy.

The fix: tell C++ how to copy. A constructor that takes const MarkList& is the copy constructor. It rents a new array of the same size and copies the values across: a deep copy.

#include <iostream>
#include <string>
using namespace std;

class MarkList {
    int n; int* data;
public:
    MarkList(int count) : n(count), data(new int[count]{}) {
        cout << "Rented " << n << " slots" << endl;
    }
    MarkList(const MarkList& o) : n(o.n), data(new int[o.n]) {
        for (int i = 0; i < n; i++) data[i] = o.data[i];
    }
    ~MarkList() { delete[] data; cout << "Returned " << n << endl; }
};

int main() {
    MarkList a(5);
    MarkList b = a;
    return 0;
}

Output:

Rented 5 slots
Returned 5
Returned 5

Two separate arrays, each returned exactly once. No crash.

  • The copy constructor runs when a new object is made from an existing one: MarkList b = a;, MarkList b(a);, and when an object is passed by value to a function.
  • Its parameter must be a reference (const MarkList&). By value, making the copy would itself need a copy, forever.
  • Inside, o.n and o.data are allowed even though they're private: private means private to the class, not to one object.

Copy assignment and the rule of three

Assigning to an object that already exists, b = a;, is a different operation (copy assignment), and it has the same problem:

#include <iostream>
using namespace std;
class MarkList {
    int n; int* data;
public:
    MarkList(int count) : n(count), data(new int[count]{}) { cout << "Rented " << n << endl; }
    ~MarkList() { delete[] data; cout << "Returned " << n << endl; }
};
int main() {
    MarkList a(5), b(3);
    b = a;
    return 0;
}

What happened:

Rented 5
Rented 3
Returned 5
free(): double free detected in tcache 2

Now b's original 3 slots are leaked and a's array is freed twice. The fix is to write operator=, which we'll do with operator overloading in episode 17.

Rule of three: if a class needs a destructor (because it owns something), it almost always needs a copy constructor and a copy assignment operator too. Later, vector (episode 21) and smart pointers (episode 28) will do all of this for you.

If a class owns memory It needs It does
Constructor yes rents it (new)
Destructor yes returns it (delete[])
Copy constructor yes rents new memory and copies the values
Copy assignment (a = b) yes same idea for an existing object (episode 17)

Common mistakes (and the real g++ messages)

Mistake Code What g++ says / what happens Fix
Creating an object without the data its only constructor needs Account c; with only Account(string, double) error: no matching function for call to 'Account::Account()' pass the data, or add Account()
A return type on a constructor void Account(string n, double b) error: return type specification for constructor invalid Account(string n, double b)
Assigning a const member in the body accNo = no; error: uninitialized const member in 'const int' and error: assignment of read-only member 'Account::accNo' : accNo(no) in the initializer list
Parameters on a destructor ~Account(int x) error: destructors may not have parameters ~Account()
Empty brackets when creating an object Account a(); a.show(); warning: empty parentheses were disambiguated as a function declaration then error: request for member 'show' in 'a', which is of non-class type 'Account()' Account a;
No destructor for a class that owns new[] memory MarkList without ~MarkList() no message: a silent memory leak ~MarkList() { delete[] data; }
Copying an object that owns memory MarkList b = a; at run time: free(): double free detected in tcache 2, aborted a copy constructor that makes a deep copy
Assigning an object that owns memory b = a; at run time: free(): double free detected in tcache 2, aborted copy assignment operator (episode 17)

Mini project: a self-cleaning list of marks

In episode 10, our average program had to remember delete[]. This MarkList can't forget: the constructor rents n slots and reads each mark from the input, average() adds them up, and the destructor returns the memory. main has no new and no delete at all.

#include <iostream>
#include <string>
using namespace std;

class MarkList {
    int n; int* data;
public:
    MarkList(int count) : n(count), data(new int[count]) {
        for (int i = 0; i < n; i++) cin >> data[i];
    }
    ~MarkList() { delete[] data; cout << "Freed " << n << endl; }
    double average() {
        int total = 0;
        for (int i = 0; i < n; i++) total = total + data[i];
        return total / double(n);
    }
};

int main() {
    int n; cin >> n;
    MarkList m(n);
    cout << "Average: " << m.average() << endl;
    return 0;
}

Input:

5
78 92 65 88 71

Output:

Average: 78.8
Freed 5

Freed 5 appears by itself when m dies at the end of main. That's the C++ way: whoever owns a resource cleans it up in its destructor.

Extend it: add highest(), and a copy constructor so a MarkList can be copied safely.

Practice

  1. Give Student a constructor that rejects marks outside 0 to 100 (store 0 and print a message instead).
  2. Add a default constructor that makes "Unknown" with 0 marks.
  3. Print messages from the constructors and destructor, then pass an object by value to a function. Predict the output first.
  4. Add highest() to MarkList.
Solution

1 and 2. Two constructors; the checking one uses the initializer list for the name and checks the marks in the body.

#include <iostream>
#include <string>
using namespace std;

class Student {
    string name;
    int marks;
public:
    Student(string n, int m) : name(n), marks(0) {
        if (m < 0 || m > 100) cout << "Rejected " << m << " for " << name << endl;
        else marks = m;
    }
    Student() : name("Unknown"), marks(0) {}
    void show() { cout << name << ": " << marks << endl; }
};

int main() {
    Student a("Ravi", 65);
    Student b("Priya", 250);
    Student c;
    a.show();
    b.show();
    c.show();
    return 0;
}

Output:

Rejected 250 for Priya
Ravi: 65
Priya: 0
Unknown: 0

3. Passing by value calls the copy constructor; the copy dies at the end of the function.

#include <iostream>
#include <string>
using namespace std;

class Account {
    string owner;
public:
    Account(string n) : owner(n) { cout << "Opened " << owner << endl; }
    Account(const Account& o) : owner(o.owner + " (copy)") { cout << "Copied " << o.owner << endl; }
    ~Account() { cout << "Closed " << owner << endl; }
};

void audit(Account x) {
    cout << "Auditing..." << endl;
}

int main() {
    Account a("Ravi");
    audit(a);
    cout << "Back in main" << endl;
    return 0;
}

Output:

Opened Ravi
Copied Ravi
Auditing...
Closed Ravi (copy)
Back in main
Closed Ravi

This is one more reason to pass objects as const Account&: no copy, no extra constructor and destructor.

4. Start from the first mark and keep the bigger one.

#include <iostream>
#include <string>
using namespace std;

class MarkList {
    int n; int* data;
public:
    MarkList(int count) : n(count), data(new int[count]) {
        for (int i = 0; i < n; i++) cin >> data[i];
    }
    ~MarkList() { delete[] data; }
    int highest() {
        int best = data[0];
        for (int i = 1; i < n; i++) if (data[i] > best) best = data[i];
        return best;
    }
};

int main() {
    int n; cin >> n;
    MarkList m(n);
    cout << "Highest: " << m.highest() << endl;
    return 0;
}

Input:

5
78 92 65 88 71

Output:

Highest: 92

Quick quiz

What does this print?

#include <iostream>
#include <string>
using namespace std;

class T {
    char c;
public:
    T(char x) { c = x; cout << c; }
    ~T() { cout << c; }
};

int main() {
    T a('A');
    { T b('B'); }
    T c('C');
    return 0;
}
  • A. ABCABC
  • B. ABBCCA
  • C. ABBCAC
  • D. ABCCBA
Answer

B: ABBCCA (verified). A is built. B is built and destroyed at the end of its own block (BB). C is built. At the end of main, the remaining objects die in reverse order: C, then A.

Interview questions

  • What is a constructor? A special member function with the class's name and no return type that runs automatically when an object is created, to put it in a valid state.
  • What is a default constructor? One that can be called with no arguments. The compiler generates an empty one only if you declare no constructors at all.
  • Why use a member initializer list? It initialises members as they are created, instead of creating them and then assigning. It is required for const members, reference members, and members without a default constructor.
  • In what order are members initialised? In the order they are declared in the class, regardless of the order in the initializer list.
  • What is a destructor and when is it called? ~ClassName(), with no parameters and no return type. It runs automatically when an object's lifetime ends: at the end of its scope for local objects, or on delete for heap objects.
  • In what order are local objects destroyed? In reverse order of construction.
  • What is the difference between a shallow copy and a deep copy? A shallow copy copies the pointer, so both objects share the same memory (leading to a double free). A deep copy allocates new memory and copies the contents.
  • What is the copy constructor, and why must its parameter be a reference? ClassName(const ClassName& other); it builds a new object from an existing one. If the parameter were by value, calling it would need a copy, which would call it again, forever.
  • What is the rule of three? If a class needs a user-defined destructor, copy constructor or copy assignment operator, it almost certainly needs all three. (Modern C++ extends it to the rule of five with move operations, episode 29.)
  • What is RAII? Resource Acquisition Is Initialization: acquire a resource in a constructor and release it in the destructor, so the resource's lifetime is tied to an object's scope and can't leak.
  • What does Account a(); declare? A function named a that takes nothing and returns an Account (the most vexing parse), not an object.

Glossary

Term Plain meaning Example
Constructor A member function, named like the class with no return type, that runs when an object is created Account(string n, double b)
Default constructor A constructor that takes no arguments Account()
Overloaded constructors Several constructors with different parameter lists Account() and Account(string, double)
Member initializer list : member(value), ... after a constructor's brackets; sets members as they're created : accNo(no), owner(n)
const member A data member that can never change after it's set const int accNo;
Initialise Give something its first value as it is created accNo(no)
Assign Change the value of something that already exists owner = n;
Destructor A member function ~ClassName() that runs when an object dies ~Account()
Tilde (~) The squiggle character that starts a destructor's name ~MarkList
Scope The block (between braces) where a name exists; a local object dies at its closing brace the inner { } block
Lifetime The time from an object's construction to its destruction t lives only inside its block
Resource Something an object must give back: heap memory, an open file, a lock the new int[] array
Memory leak Memory that is rented but never returned MarkList without a destructor
RAII Resource Acquisition Is Initialization: get it in the constructor, release it in the destructor MarkList
Shallow copy Copying a pointer, so two objects share one block of memory MarkList b = a; with no copy constructor
Deep copy Copying the memory itself, so each object owns its own block the copy constructor above
Copy constructor A constructor that builds a new object from an existing one MarkList(const MarkList& o)
Copy assignment Assigning one existing object to another b = a;
Double free Deleting the same memory twice; the program is aborted free(): double free detected in tcache 2
Aborted The program stopped itself after detecting a serious memory error after the double free
Rule of three Needs a destructor → also needs a copy constructor and copy assignment MarkList
Most vexing parse Account a(); read as a function declaration, not an object use Account a;
Pass by value The function gets a copy, made by the copy constructor void audit(Account x)

Summary

  • An object that must be set up by a separate function call will be set up wrong someday: we printed garbage.
  • A constructor (class name, no return type) runs automatically when the object is created. With required parameters, Account c; becomes a compile error: no matching function for call to 'Account::Account()'.
  • Constructors can be overloaded; Account() is the default constructor. Write any constructor and the free default one disappears.
  • The member initializer list : accNo(no), owner(n) sets members as they are built; const and reference members need it.
  • A destructor ~Account() runs automatically at the end of the object's scope; objects die in reverse order.
  • A class that owns memory rents it in the constructor and returns it in the destructor (RAII), so it can't leak.
  • Copying such a class copies the pointer (shallow copy) and crashes with double free detected. A copy constructor makes a deep copy. Remember the rule of three.

Next episode: access specifiers and encapsulation. Our classes now start correct and clean up after themselves. Next: how the outside world should read and change private data safely with getters and setters, and what the third label, protected, is for.