AdvancedC++ Programming · Lesson 11 of 17 · Updated ·
Copy Constructor in C++ — Shallow vs Deep Copy, Copy Assignment and the Rule of Three
Copying an int is simple: the bits are copied. Copying an object is a decision. If the object owns memory through a pointer, should the copy share that memory or get its own? Get it wrong and the program crashes when the objects are destroyed. This lesson explains the copy constructor and copy assignment, the two functions that control copying — a favourite topic in C++ vivas and interviews.
1. When does C++ copy an object?
The copy constructor creates a new object as a copy of an existing one. Its signature is:
ClassName(const ClassName &other);
It runs in these situations:
| Situation | Example |
|---|---|
| A new object is initialised from another | Student b = a; or Student b(a); |
| An object is passed by value to a function | void show(Student s); then show(a); |
| An object is returned by value (unless the compiler skips the copy) | return local; |
Copy assignment is different: it copies into an object that already exists: b = a; where b was created earlier.
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
Student(string n) : name(n) { cout << "construct " << name << "\n"; }
Student(const Student &o) : name(o.name) { cout << "copy-construct " << name << "\n"; }
Student &operator=(const Student &o) {
cout << "copy-assign " << o.name << " into " << name << "\n";
name = o.name;
return *this;
}
};
void by_value(Student s) { } // receives a copy
void by_ref(const Student &s) { } // no copy
int main() {
Student a("Asha");
Student b = a; // new object: copy constructor
Student c("Ravi");
c = a; // existing object: copy assignment
by_value(a); // copy constructor again
by_ref(a); // nothing printed
return 0;
}
construct Asha
copy-construct Asha
construct Ravi
copy-assign Asha into Ravi
copy-construct Asha
Student b = a; uses = but it is not assignment — b is being created, so the copy constructor runs. A quick rule: new object → constructor; existing object → assignment.
Passing by const & avoids the copy entirely. That is why large objects are usually passed as const T &.
2. The default copy is a shallow copy
If you do not write a copy constructor, the compiler generates one that copies each member. For string, vector and other well-behaved members this is perfect, because they copy themselves properly.
The problem is a raw pointer member. Copying a pointer copies the address, not the data it points to. Both objects now point to the same memory. This is a shallow copy.
Here is a class that owns an array of marks, with no copy constructor:
#include <iostream>
using namespace std;
class Marks {
public:
int *data;
int n;
Marks(int n) : data(new int[n]{}), n(n) {}
// no copy constructor written: the compiler copies the pointer
};
int main() {
Marks a(3);
a.data[0] = 70;
Marks b = a; // shallow copy: b.data == a.data
b.data[0] = 99; // changes a too!
cout << a.data[0] << " " << (a.data == b.data) << "\n";
delete[] a.data; // only one delete, because they share it
return 0;
}
99 1
Changing b changed a, because they share one array. Worse, if Marks had a destructor with delete[] data;, both a and b would delete the same array when they go out of scope — a double delete, which is undefined behaviour and often crashes.
3. Writing a deep copy
A deep copy allocates new memory for the copy and copies the values. Each object then owns its own data.
#include <iostream>
using namespace std;
class Marks {
int *data;
int n;
public:
Marks(int n) : data(new int[n]{}), n(n) {}
Marks(const Marks &o) : data(new int[o.n]), n(o.n) { // deep copy
for (int i = 0; i < n; i++) data[i] = o.data[i];
cout << "deep copy\n";
}
~Marks() { delete[] data; }
void set(int i, int v) { data[i] = v; }
int get(int i) const { return data[i]; }
};
int main() {
Marks a(3);
a.set(0, 70);
Marks b = a; // b gets its own array
b.set(0, 99);
cout << a.get(0) << " " << b.get(0) << "\n";
return 0;
} // each destructor frees its own array: safe
deep copy
70 99
4. Copy assignment and self-assignment
The class above is still unsafe: b = a; (assignment) would use the compiler's version, which copies the pointer, leaks b's old array and causes a double delete later. We must also write operator=.
Assignment has two extra jobs compared with the copy constructor:
- Release the old memory that the object already owns.
- Handle self-assignment (
a = a;) — if you delete your data first, you destroy the very thing you are copying from.
The cleanest way to get both right is the copy-and-swap idiom: take the parameter by value (which makes a copy using the copy constructor), then swap your contents with that copy. The old data ends up in the parameter and is freed when it goes out of scope.
#include <iostream>
#include <utility>
using namespace std;
class Marks {
int *data;
int n;
public:
Marks(int n) : data(new int[n]{}), n(n) {}
Marks(const Marks &o) : data(new int[o.n]), n(o.n) {
for (int i = 0; i < n; i++) data[i] = o.data[i];
}
Marks &operator=(Marks o) { // o is already a deep copy
swap(data, o.data); // take o's array, give it ours
swap(n, o.n);
return *this; // o is destroyed here, freeing our old array
}
~Marks() { delete[] data; }
void set(int i, int v) { data[i] = v; }
int get(int i) const { return data[i]; }
int size() const { return n; }
};
int main() {
Marks a(2), b(5);
a.set(0, 88);
b = a; // b's old 5-int array is freed, b gets a copy of a
a.set(0, 10);
cout << b.get(0) << " " << b.size() << "\n";
b = b; // self-assignment: still correct
cout << b.get(0) << "\n";
return 0;
}
88 2
88
operator= returns *this by reference so that chains like a = b = c; work, just as they do for ints.
5. The rule of three — and the rule of zero
Rule of three: if a class needs a custom destructor, copy constructor or copy assignment operator, it almost certainly needs all three. The reason is always the same: the class manages a resource (memory, a file, a network connection) by hand.
(In modern C++ this becomes the rule of five, adding the move constructor and move assignment, covered in the move semantics lesson.)
Rule of zero: the best design avoids the problem altogether. Use members that already copy themselves correctly — vector<int> instead of int *, string instead of char *, smart pointers for ownership. Then you write none of the three, and the compiler-generated versions are correct.
#include <iostream>
#include <vector>
using namespace std;
class Marks { // rule of zero: no destructor, no copy code
vector<int> data;
public:
Marks(int n) : data(n) {}
void set(int i, int v) { data[i] = v; }
int get(int i) const { return data[i]; }
};
int main() {
Marks a(3);
a.set(1, 75);
Marks b = a; // vector makes a deep copy for us
b.set(1, 40);
cout << a.get(1) << " " << b.get(1) << "\n";
return 0;
}
75 40
6. Preventing copies
Some objects should never be copied — a bank account, a file handle, a database connection. Delete the copy operations, and any attempt to copy becomes a compile error:
class Account {
public:
Account() = default;
Account(const Account &) = delete;
Account &operator=(const Account &) = delete;
};
unique_ptr and std::thread are non-copyable in exactly this way.
Common mistakes
- Thinking
T b = a;callsoperator=— it calls the copy constructor. - Writing the copy constructor parameter by value:
T(T other). Passing by value needs a copy, which needs the copy constructor — infinite recursion, so the compiler rejects it. It must beconst T &. - Keeping a raw owning pointer with the default (shallow) copy: shared data and double delete.
- Writing a copy constructor and destructor but forgetting copy assignment.
- In a hand-written
operator=, deleting the old data before checking for self-assignment.
Quick recap
- Copy constructor: makes a new object (
T b = a;, pass by value, return by value). - Copy assignment: overwrites an existing object (
b = a;). - The default copy is member-wise; for a raw pointer that means a shallow copy.
- A deep copy allocates new memory and copies the values.
- Copy-and-swap gives a safe
operator=that handles self-assignment. - Rule of three: destructor, copy constructor, copy assignment go together. Rule of zero: use
vector,stringand smart pointers so you need none.