Lesson 17 +35 XP

Copy Constructors, Dynamic Constructors & Destructors

Copy Constructors, Dynamic Constructors & Destructors

This lesson completes the story of an object's life. A copy constructor creates an object as a copy of another. A dynamic constructor allocates memory for each object at run time. A destructor cleans up when the object dies. Together they explain one of the most asked questions in C++: shallow copy vs deep copy.

1. Copy Constructor

A copy constructor initialises a new object from an existing object of the same class. It takes a reference to an object of its own class as its argument:

ClassName (texttt{const} ClassName \& obj);

It is called in three situations:

  1. When an object is declared and initialised from another: Code B(A); or Code B = A;
  2. When an object is passed by value to a function (the parameter is a copy).
  3. When a function returns an object by value (compilers may skip this copy as an optimisation).

It is not called for assignment between two existing objects: B = A; (with B already created) uses the assignment operator instead.

C++
#include <iostream>
using namespace std;

class Code {
    int id;

public:
    Code() {
        id = 0;
    }
    Code(int a) {
        id = a;
    }
    Code(const Code& x) { // copy constructor
        id = x.id;
        cout << "copy constructor called" << endl;
    }
    void display() {
        cout << id << endl;
    }
};

void show(Code c) { // pass by value: a copy is made
    cout << "in show(): ";
    c.display();
}

int main() {
    Code A(100);
    Code B(A);  // copy constructor
    Code C = A; // copy constructor again
    Code D;
    D = A; // assignment: NOT the copy constructor

    cout << "id of A: ";
    A.display();
    cout << "id of B: ";
    B.display();
    cout << "id of C: ";
    C.display();
    cout << "id of D: ";
    D.display();
    show(A);
    return 0;
}

Output:

OUTPUT
copy constructor called
copy constructor called
id of A: 100
id of B: 100
id of C: 100
id of D: 100
copy constructor called
in show(): 100

Why must the argument be a reference?

If the copy constructor took its argument by value, Code(Code x), then passing A to it would need a copy of A, which would call the copy constructor, which would need a copy... an infinite recursion.

So the compiler does not allow it. The argument is a reference, usually const so that the original cannot be changed and temporary objects can be copied too.

If no copy constructor is written, the compiler supplies a default copy constructor that copies every data member one by one (member-wise copy).

2. Shallow Copy vs Deep Copy

The default member-wise copy is fine for simple members. It goes wrong when a class holds a pointer to memory it allocated: the copy gets the same pointer, so two objects share one block of memory. This is a shallow copy.

Shallow copy shares one buffer; deep copy gives each object its ownShallow copy shares one buffer; deep copy gives each object its own

Shallow copyDeep copy
copies the pointer value onlyallocates new memory and copies the data it points to
both objects point to the same memoryeach object has its own memory
a change through one object shows up in the otherobjects are independent
when both destructors run, the memory is deleted twice (a crash or undefined behaviour)each destructor frees its own memory safely
the default copy constructor does thisneeds a user-defined copy constructor
C++
#include <iostream>
#include <cstring>
using namespace std;

class Name {
    char* text;

public:
    Name(const char* s) {
        text = new char[strlen(s) + 1]; // dynamic allocation
        strcpy(text, s);
    }
    Name(const Name& other) { // deep copy constructor
        text = new char[strlen(other.text) + 1];
        strcpy(text, other.text); // copy the characters, not the pointer
    }
    ~Name() {
        delete[] text;
    } // each object frees its own buffer
    void setFirst(char c) {
        text[0] = c;
    }
    void show() {
        cout << text << endl;
    }
};

int main() {
    Name a("Rahul");
    Name b(a);       // deep copy: b gets its own buffer
    b.setFirst('M'); // change only b
    cout << "a: ";
    a.show();
    cout << "b: ";
    b.show();
    return 0;
}

Output:

OUTPUT
a: Rahul
b: Mahul

Without the user-defined copy constructor, b.setFirst('M') would also change a, and the program would delete the same buffer twice at the end.

ℹ️ Note

Rule of three: if a class needs a user-defined destructor, copy constructor or copy assignment operator, it almost certainly needs all three, because all of them deal with the same owned resource.

3. Dynamic Constructors

A constructor that allocates memory with new while the object is being created is called a dynamic constructor. It lets each object get exactly as much memory as it needs, which is useful when objects of the same class have different sizes (strings of different lengths, matrices of different orders).

C++
#include <iostream>
#include <cstring>
using namespace std;

class String {
    char* name;
    int length;

public:
    String() { // empty string
        length = 0;
        name = new char[length + 1];
        name[0] = '\0';
    }
    String(const char* s) { // dynamic constructor
        length = strlen(s);
        name = new char[length + 1]; // exactly the memory needed
        strcpy(name, s);
    }
    ~String() {
        delete[] name;
    }
    void display() {
        cout << name << " (" << length << " chars)" << endl;
    }
    void join(const String& a, const String& b);
};

void String::join(const String& a, const String& b) {
    length = a.length + b.length;
    delete[] name;               // free the old buffer
    name = new char[length + 1]; // allocate the new size
    strcpy(name, a.name);
    strcat(name, b.name);
}

int main() {
    String name1("Joseph ");
    String name2("Louis ");
    String name3("Lagrange");
    String s1, s2;
    s1.join(name1, name2);
    s2.join(s1, name3);
    name1.display();
    name2.display();
    name3.display();
    s1.display();
    s2.display();
    return 0;
}

Output:

OUTPUT
Joseph  (7 chars)
Louis  (6 chars)
Lagrange (8 chars)
Joseph Louis  (13 chars)
Joseph Louis Lagrange (21 chars)

A dynamic two-dimensional array

C++
#include <iostream>
using namespace std;

class Matrix {
    int** p;
    int rows, cols;

public:
    Matrix(int r, int c) { // dynamic constructor
        rows = r;
        cols = c;
        p = new int*[rows]; // array of row pointers
        for (int i = 0; i < rows; i++) {
            p[i] = new int[cols]; // each row
        }
    }
    ~Matrix() {
        for (int i = 0; i < rows; i++) {
            delete[] p[i];
        }
        delete[] p;
    }
    void fill() {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                p[i][j] = (i + 1) * (j + 1);
            }
        }
    }
    void show() {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                cout << p[i][j] << " ";
            }
            cout << endl;
        }
    }
};

int main() {
    Matrix m(3, 4); // size decided at run time
    m.fill();
    m.show();
    return 0;
}

Output:

OUTPUT
1 2 3 4 
2 4 6 8 
3 6 9 12 

4. Destructors

A destructor destroys an object: it is called automatically when the object goes out of scope (or when delete is used on an object created with new). Its job is to release resources the object holds: memory from new, open files, network connections.

simClassName() { dots }

Characteristics of destructors

  1. It has the same name as the class, preceded by a tilde ~.
  2. It takes no arguments and returns no value (not even void).
  3. So it cannot be overloaded: a class has exactly one destructor.
  4. It is invoked implicitly when the object goes out of scope (end of block, end of program, or delete).
  5. Objects are destroyed in the reverse order of their creation.
  6. It can be virtual (and should be in a base class with virtual functions, Lesson 29).
  7. It should be declared public.
  8. If none is written, the compiler supplies one that does nothing special.
C++
#include <iostream>
using namespace std;

int objectCount = 0;

class Alpha {
    int id;

public:
    Alpha() {
        id = ++objectCount;
        cout << "Created object " << id << endl;
    }
    ~Alpha() {
        cout << "Destroyed object " << id << endl;
    }
};

int main() {
    cout << "Enter main" << endl;
    Alpha a1, a2;
    {
        cout << "Enter block" << endl;
        Alpha a3, a4;
        cout << "Leave block" << endl;
    } // a4 then a3 are destroyed here
    Alpha* p = new Alpha; // dynamic object
    delete p;             // destructor runs now
    cout << "Leave main" << endl;
    return 0;
} // a2 then a1 are destroyed here

Output:

OUTPUT
Enter main
Created object 1
Created object 2
Enter block
Created object 3
Created object 4
Leave block
Destroyed object 4
Destroyed object 3
Created object 5
Destroyed object 5
Leave main
Destroyed object 2
Destroyed object 1

5. Constructor vs Destructor

ConstructorDestructor
initialises an objectdestroys an object (releases its resources)
name: ClassNamename: ~ClassName
can take argumentstakes no arguments
can be overloaded (many per class)cannot be overloaded (one per class)
cannot be virtualcan be virtual
called when the object is createdcalled when the object goes out of scope or is deleted
objects are constructed in order of declarationobjects are destroyed in reverse order
💡 Tip

Key points to remember

  • Copy constructor: A(const A& x); called for A b(a), A b = a, pass by value and return by value; not for b = a.
  • Its argument must be a reference, otherwise copying it would recurse forever.
  • Default copy = member-wise (shallow). Classes owning new memory need a deep copy constructor.
  • Dynamic constructor: allocates with new inside the constructor; pair it with delete in the destructor.
  • Destructor: ~A(), no arguments, no overloading, runs automatically, objects die in reverse order.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is a copy constructor? When is it invoked? Why is its argument passed by reference? (5 Marks)
  • Write: the syntax, the three situations (and that b = a is not one), the Code program, and the infinite-recursion argument.
  • Q2. Differentiate between shallow copy and deep copy with a program. (10 Marks)
  • Write: the diagram, the comparison table, and the Name class with its deep copy constructor and destructor.
  • Q3. What is a dynamic constructor? Write a program to join two strings using it. (5 Marks)
  • Q4. What is a destructor? Write a program showing the order in which objects are created and destroyed. (5 Marks)
  • Write: the eight characteristics and the Alpha program with its output.
  • Q5. Differentiate between a constructor and a destructor. (2.5 Marks)