Loading lessons...
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:
It is called in three situations:
- When an object is declared and initialised from another:
Code B(A);orCode B = A; - When an object is passed by value to a function (the parameter is a copy).
- 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.
#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:
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(): 100Why 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 own
| Shallow copy | Deep copy |
|---|---|
| copies the pointer value only | allocates new memory and copies the data it points to |
| both objects point to the same memory | each object has its own memory |
| a change through one object shows up in the other | objects 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 this | needs a user-defined copy constructor |
#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:
a: Rahul
b: MahulWithout the user-defined copy constructor, b.setFirst('M') would also change a, and the program would delete the same buffer twice at the end.
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).
#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:
Joseph (7 chars)
Louis (6 chars)
Lagrange (8 chars)
Joseph Louis (13 chars)
Joseph Louis Lagrange (21 chars)A dynamic two-dimensional array
#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:
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.
Characteristics of destructors
- It has the same name as the class, preceded by a tilde
~. - It takes no arguments and returns no value (not even
void). - So it cannot be overloaded: a class has exactly one destructor.
- It is invoked implicitly when the object goes out of scope (end of block, end of program, or
delete). - Objects are destroyed in the reverse order of their creation.
- It can be
virtual(and should be in a base class with virtual functions, Lesson 29). - It should be declared
public. - If none is written, the compiler supplies one that does nothing special.
#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 hereOutput:
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 15. Constructor vs Destructor
| Constructor | Destructor |
|---|---|
| initialises an object | destroys an object (releases its resources) |
name: ClassName | name: ~ClassName |
| can take arguments | takes no arguments |
| can be overloaded (many per class) | cannot be overloaded (one per class) |
| cannot be virtual | can be virtual |
| called when the object is created | called when the object goes out of scope or is deleted |
| objects are constructed in order of declaration | objects are destroyed in reverse order |
Key points to remember
- Copy constructor:
A(const A& x); called forA b(a),A b = a, pass by value and return by value; not forb = a. - Its argument must be a reference, otherwise copying it would recurse forever.
- Default copy = member-wise (shallow). Classes owning
newmemory need a deep copy constructor. - Dynamic constructor: allocates with
newinside the constructor; pair it withdeletein the destructor. - Destructor:
~A(), no arguments, no overloading, runs automatically, objects die in reverse order.
📝 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 = ais not one), theCodeprogram, 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
Nameclass 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
Alphaprogram with its output. - Q5. Differentiate between a constructor and a destructor. (2.5 Marks)