Course Materials

OOP - Week 2, Lecture 3: Copy Constructor and Destructors

Copying an Object

Sometimes we need a new object that starts out as a copy of an existing one:

Date a(7, 10, 2023);
Date b = a;                  // b should start with the same values as a

Creating b needs a constructor, so C++ needs one that builds an object from another object of the same class. That is the copy constructor.

You do not always have to write it. If you do not, the compiler creates a copy constructor that copies every data member one by one. This member-by-member copy is called a shallow copy. For a class like Date, a shallow copy is exactly what we want, because every member is a plain number.

A shallow copy stops being enough when an object holds a pointer to memory it allocated. Copying the pointer gives two objects that share the same memory, so changing one changes the other. For that case we need a deep copy, which copies the memory as well. We will study this in Week 5, together with dynamic memory.

1. The Copy Constructor

A copy constructor is a constructor whose only parameter is a reference to an object of its own class:

ClassName(const ClassName& other) {
    // copy every data member of other into the new object
}

For Date:

Date(const Date& other) {
    day = other.day;
    month = other.month;
    year = other.year;
}
  • other is the object being copied.
  • Inside the class, we can read the private members of other, because it is also a Date.

Why const and &?

The parameter const ClassName& other has two parts, and each one has a job:

  • & (reference): other is not a new object. It is another name for the object being copied, so nothing is copied just to call the copy constructor. This is also required. If the parameter were passed by value, C++ would have to copy the argument into it, and that copy would need the copy constructor again, forever. Section 3 explains this.
  • const: a promise that the constructor only reads other and never changes it. A copy should never change the original, so const lets the compiler catch a mistake such as other.day = 5;. It also lets you copy from objects that are themselves const. We will study const in Week 4. For now, always write const in a copy constructor.
Date(const Date& other) {
    day = other.day;         // reading other is fine
    // other.day = 5;        // error: other is const
}

Two ways to ask for a copy when you create an object:

Date b(a);                   // copy constructor
Date c = a;                  // copy constructor too

Date c = a; creates a new object, so it runs the copy constructor. A later b = a; on an object that already exists is an assignment, not a copy constructor call.

2. When Does the Copy Constructor Run?

It runs in three situations:

CaseSituationExample
1Creating an object from another objectDate b = a; or Date b(a);
2Passing an object to a function by valueshow(a); where void show(Date d)
3Returning an object from a function by valueDate make() { Date d; return d; }

Passing by value gives the function its own copy of the argument, so the function can change the copy without touching the original. If a function takes its parameter by reference (void show(Date& d)), nothing is copied and the copy constructor does not run.

In situation 3 the compiler is allowed to skip the copy and build the returned object directly where it is needed. Most compilers do this, so you may not see the copy constructor run when a function returns an object.

3. Why the Parameter Must Be a Reference

Why Date(const Date& other) and not Date(Date other)?

Important: The copy constructor must take its parameter by reference (&). Never write Date(Date other).

If the parameter were passed by value, then to call the copy constructor C++ would first have to copy the argument into other. That copy needs the copy constructor again, which needs another copy, and so on forever. The compiler refuses to compile this and reports an error like β€œcopy constructor must pass its first argument by reference”. The exact words depend on your compiler.

Date(Date other) { ... }          // error: would copy forever
Date(const Date& other) { ... }   // correct

4. Destructors

A destructor is the opposite of a constructor. It is a special member function that C++ runs automatically when an object’s life ends.

  • Its name is a ~ followed by the class name: ~Date().
  • It has no parameters and no return type, so a class can have only one.
  • If you do not write one, the compiler creates a destructor that does nothing.
  • It is used for cleaning up. In Week 5 it will free memory that the object allocated.
~Date() {
    cout << "destructor " << day << "/" << month << "/" << year << endl;
}

An object’s life ends when:

  • a local object reaches the end of the block { } where it was declared. An object declared in main is destroyed when main ends.
  • a parameter passed by value reaches the end of the function. It was a copy, and the copy is destroyed when the function call is finished.

5. Order of Constructors and Destructors

  • Constructors run in the order the objects are created, which is the order of the declarations. A copy is created by a constructor too, so it counts.
  • Destructors run in the reverse order. The object created last is destroyed first.

You can remember it like a stack of plates: the last plate you put on is the first one you take off.

The program below has a function show that takes its parameter by value and a function showRef that takes it by reference. Press Step to run it one event at a time. The panel on the right shows the objects that are alive. A new object lands on top of the stack, and only the object on top can be destroyed, which is why destruction happens in the reverse order.

void show(Date d) {        // by value
    d.print();
}                          // d is destroyed here

void showRef(Date& d) {    // by reference
    d.print();
}

int main() {
    Date a(1, 1, 2001);
    Date b(2, 2, 2002);
    Date c = a;            // copy constructor
    show(b);               // d is a copy of b
    showRef(c);            // no copy is made
    return 0;
}                          // destructors run here

The step-by-step view needs JavaScript. The code of the program is shown above.

  • show(b) copies b into the parameter d, so the copy constructor runs, and d is destroyed when show ends.
  • showRef(c) works on c itself, so nothing is created and nothing is destroyed.

6. Putting It Together

To watch all of this happen, the program below prints a message from every constructor and from the destructor. Then main creates objects, copies one, passes one to a function by value, and ends. The green lines are what changed since Lecture 2.

Date lifecycle tracecode/oop/week-02/date-3
added since Lecture 2 has a note
#include <iostream>
using namespace std;

class Date {
private:
    int day, month, year;

public:
    Date() {                            // default constructor
        day = 1;
        month = 1;
        year = 2000;
        cout << "default constructor " << day << "/" << month << "/" << year << endl;
    }
    Date(int d, int m, int y) {         // parameterized constructor
        day = 1;
        month = 1;
        year = 2000;
        setDay(d);
        setMonth(m);
        setYear(y);
        cout << "constructor " << day << "/" << month << "/" << year << endl;
    }
    Date(const Date& other) {           // copy constructor
        day = other.day;
        month = other.month;
        year = other.year;
        cout << "copy constructor " << day << "/" << month << "/" << year << endl;
    }
    ~Date() {                           // destructor
        cout << "destructor " << day << "/" << month << "/" << year << endl;
    }

    void setDay(int d) {
        if (d < 1 || d > 31)            // validation
            return;
        day = d;
    }
    void setMonth(int m) {
        if (m < 1 || m > 12)            // validation
            return;
        month = m;
    }
    void setYear(int y) {
        if (y < 1)                      // validation
            return;
        year = y;
    }

    int getDay() {
        return day;
    }
    int getMonth() {
        return month;
    }
    int getYear() {
        return year;
    }

    void print() {
        cout << day << "/" << month << "/" << year << endl;
    }
};

void show(Date d) {                     // d is a copy of the argument
    cout << "inside show: ";
    d.print();
}                                       // d is destroyed here

int main() {
    cout << "start of main" << endl;
    Date a(1, 1, 2001);
    Date b(2, 2, 2002);
    Date c = a;                         // copy constructor
    cout << "calling show" << endl;
    show(b);                            // copy constructor for the parameter
    cout << "back in main" << endl;
    return 0;
}                                       // destructors run here: c, b, a
Terminal
g++ main.cpp -o app
./app
Tip: click a line of output to jump to the code that printed it.Output hidden. Try it yourself first.

Click each line of output in the terminal to see what caused it.