Copy Constructor in C++
In this lesson: When copy constructors run in C++, shallow vs deep copy and the rule of three — with output. In Hindi & English.
What is a copy constructor?
A copy constructor builds a new object as a copy of an existing one. It has a special signature — it takes a reference to another object of the same class:
class Point {
public:
int x, y;
Point(int a, int b) : x(a), y(b) { }
Point(const Point &p) : x(p.x), y(p.y) { // copy constructor
cout << "Copied\n";
}
};When is it called?
- Initialising one object from another:
Point b = a; - Passing an object to a function by value.
- Returning an object by value from a function.
The compiler-provided copy
If you write none, the compiler makes one that copies each member. For simple classes (only plain values) this is perfect and you need not write your own.
Shallow copy problem
The trouble appears when a class holds a pointer. The default copy duplicates the pointer value, so both objects point at the same memory:
class Buffer {
public:
int *data;
Buffer(int v) { data = new int(v); }
~Buffer() { delete data; }
// no copy constructor → shallow copy
};
// Buffer b2 = b1; → both share the same data pointer!
// when both destruct → double free (crash)Writing a deep copy
A deep copy allocates fresh memory so each object owns its own data:
class Buffer {
public:
int *data;
Buffer(int v) { data = new int(v); }
Buffer(const Buffer &b) { // deep copy
data = new int(*b.data); // new memory, copy value
}
~Buffer() { delete data; }
};Now each Buffer has its own data, so destroying one does not affect the other.
The rule of three
If a class needs a custom copy constructor, it almost always also needs a custom destructor and copy assignment operator — the rule of three. Modern C++ often sidesteps all of this by using smart pointers, which copy safely on their own.
Common mistakes
- Relying on the default shallow copy for a class that owns a pointer.
- Forgetting
constand the reference inconst ClassName&. - Writing a copy constructor but forgetting the matching destructor/assignment (rule of three).
- Passing big objects by value (triggering copies) when a
constreference would do.
Write a class holding a dynamically allocated array. Give it a deep-copy copy constructor and a destructor. Create an object, copy it, change one copy, and confirm the other is unaffected.
Summary
- A copy constructor makes a new object from an existing one.
- It is called on copy-initialisation and pass/return by value.
- The default copy is shallow — unsafe for classes owning pointers.
- Write a deep copy so each object owns its own resource.
- A custom copy constructor usually means the rule of three applies.
Frequently Asked Questions
What is a copy constructor in C++?
ClassName(const ClassName &other), and is used whenever an object is initialised from another.