Free tutorials & notes in Hindi & English · Clean code examples · Mobile friendly learning
📘 Lesson  ·  Lesson 69

Copy Constructor

Written and reviewed by · Senior IT Faculty · 15+ years’ experience

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:

C++
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:

C++
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:

C++
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 const and the reference in const ClassName&.
  • Writing a copy constructor but forgetting the matching destructor/assignment (rule of three).
  • Passing big objects by value (triggering copies) when a const reference would do.
🏋️ Practice

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++?
A copy constructor is a special constructor that creates a new object as a copy of an existing one. It takes a reference to another object of the same class, written ClassName(const ClassName &other), and is used whenever an object is initialised from another.
When is the copy constructor called in C++?
It is called when you initialise an object from another object, pass an object to a function by value, or return an object by value. In each case a new copy of the object is created using the copy constructor.
What is the difference between shallow copy and deep copy in C++?
A shallow copy duplicates member values directly, so if a member is a pointer, both objects end up sharing the same memory. A deep copy allocates new memory and copies the pointed-to data, giving each object its own independent copy. Classes that own pointers usually need a deep copy.
Does C++ provide a copy constructor automatically?
Yes. If you do not write one, the compiler generates a default copy constructor that copies each member. This works fine for simple classes, but it performs a shallow copy, which is unsafe for classes that manage raw pointers or other resources.
Why does a class with a pointer need a custom copy constructor?
Because the default shallow copy makes two objects share the same pointer, so when one is destroyed and frees the memory, the other is left with a dangling pointer, and destroying it too causes a double free. A deep-copying copy constructor gives each object its own memory to avoid this.

Copy constructor क्या है?

Copy constructor किसी मौजूदा object की copy के रूप में नया object बनाता है। इसका एक विशेष signature है — यह उसी class के दूसरे object का reference लेता है:

C++
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";
    }
};

यह कब call होता है?

  • एक object को दूसरे से initialise करना: Point b = a;
  • Object को function को value से भेजना।
  • Function से object को value से return करना।

Compiler का दिया copy

अगर आप कोई न लिखें, compiler एक बनाता है जो हर member को copy करता है। सरल classes (केवल सादी values) के लिए यह बिल्कुल सही है और आपको अपना लिखने की ज़रूरत नहीं।

Shallow copy समस्या

दिक्कत तब आती है जब class एक pointer रखती है। Default copy pointer value को नकल करता है, तो दोनों objects वही memory पर इशारा करते हैं:

C++
class Buffer {
public:
    int *data;
    Buffer(int v) { data = new int(v); }
    ~Buffer() { delete data; }
    // koi copy constructor nahi → shallow copy
};
// Buffer b2 = b1;  → dono same data pointer share karte hain!
// jab dono destruct hote hain → double free (crash)

Deep copy लिखना

Deep copy नई memory allocate करता है ताकि हर object अपना data रखे:

C++
class Buffer {
public:
    int *data;
    Buffer(int v) { data = new int(v); }
    Buffer(const Buffer &b) {          // deep copy
        data = new int(*b.data);       // nai memory, value copy
    }
    ~Buffer() { delete data; }
};

अब हर Buffer का अपना data है, तो एक को नष्ट करना दूसरे को प्रभावित नहीं करता।

Rule of three

अगर किसी class को custom copy constructor चाहिए, तो लगभग हमेशा उसे custom destructor और copy assignment operator भी चाहिए — rule of three। आधुनिक C++ अक्सर smart pointers इस्तेमाल करके इस सबसे बच जाता है, जो खुद सुरक्षित रूप से copy होते हैं।

आम गलतियाँ

  • Pointer रखने वाली class के लिए default shallow copy पर निर्भर रहना।
  • const ClassName& में const और reference भूलना।
  • Copy constructor लिखना पर मिलता destructor/assignment भूलना (rule of three)।
  • बड़े objects को value से भेजना (copies पैदा करना) जब const reference काफ़ी होता।
🏋️ अभ्यास

एक class लिखें जो dynamically allocated array रखे। इसे deep-copy copy constructor और destructor दें। एक object बनाएँ, उसे copy करें, एक copy बदलें, और पुष्टि करें कि दूसरा अप्रभावित है।

सारांश

  • Copy constructor मौजूदा object से नया object बनाता है।
  • यह copy-initialisation और value से pass/return पर call होता है।
  • Default copy shallow है — pointers रखने वाली classes के लिए असुरक्षित।
  • Deep copy लिखें ताकि हर object अपना resource रखे।
  • Custom copy constructor का मतलब आमतौर पर rule of three लागू होता है।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।