01 / 21

Copy Constructor &
Assignment Operator

Learn how C++ copies objects behind the scenes: when constructors fire, when assignment kicks in, and how to write both correctly.

C++

What Is an Object Copy?

In C++, every class instance lives in memory. When you need a second object with the same data, the compiler performs a copy. But how that copy happens depends on the context: are you creating a brand-new object, or overwriting an existing one?

Copy Constructor
Creates a new object as a clone of an existing one.
Assignment Operator
Overwrites an existing object's data with another's.

When Does Each One Fire?

Object A (already exists) copy ctor Object B (new) created right now Object A (already exists) operator= Object B (exists) already constructed INIT ASSIGN

Why Should You Care?

C++ gives you low-level control over memory. If your class manages a raw pointer, the compiler's default copy just duplicates the pointer address: both objects point to the same memory. This is a shallow copy and it leads to crashes.

Shallow Copy
Copies the pointer value. Two objects share one block of memory. Deleting one corrupts the other.
Deep Copy
Allocates new memory and copies the contents. Each object owns its own independent data.

Shallow vs Deep Copy

Shallow Copy obj1.ptr obj2.ptr Heap Data Both point to same memory! Deep Copy obj1.ptr obj2.ptr Data A Data B Each owns separate memory ✓ Writing your own copy constructor and operator= lets you choose deep copy and avoid double-free bugs.

The Copy Constructor Signature

class MyClass { public: // Copy constructor: takes a const reference to the same type MyClass(const MyClass& other); };
1
Same class name as the constructor: it is a constructor, not a regular method.
2
const reference parameter: prevents accidental modification of the source and avoids infinite recursion.
3
No return type: like all constructors, it returns nothing (not even void).

The Assignment Operator Signature

class MyClass { public: // Assignment operator: returns a reference for chaining MyClass& operator=(const MyClass& other); };
1
Returns a reference to *this: enables chaining like a = b = c.
2
operator= is the function name: C++ lets you overload the = symbol.
3
const reference parameter: same reasoning as the copy constructor.

Initialization vs Assignment

MyClass a; // default constructor MyClass b = a; // copy CONSTRUCTOR (b is brand new) MyClass c(a); // copy CONSTRUCTOR (same thing) MyClass d; d = a; // ASSIGNMENT operator (d already exists)

Other Trigger Scenarios

The copy constructor also fires in these common situations:

Pass by Value
Passing an object to a function by value creates a copy of the argument.
Return by Value
Returning an object from a function may invoke the copy constructor (before optimization).
Container Insert
Pushing an object into a std::vector or other container copies it.

How to Write Both Correctly

1
Copy Constructor: Allocate new memory, then copy the values from other's resource into your new memory.
2
Assignment Operator: First check for self-assignment (this != &other). Then free your old memory, allocate new memory, and copy.
3
Return *this from operator= so that chained assignment (a = b = c) works correctly.
4
Don't forget the destructor! If you manage memory, the Rule of Three says you need all three: destructor, copy constructor, and operator=.

Example: IntBox Class

class IntBox { int* data; public: IntBox(int val) : data(new int(val)) {} ~IntBox() { delete data; } // Copy constructor IntBox(const IntBox& other) : data(new int(*other.data)) {} // Assignment operator IntBox& operator=(const IntBox& other) { if (this != &other) { delete data; data = new int(*other.data); } return *this; } };

Tracing Which Gets Called

IntBox x(42); // regular constructor IntBox y = x; // copy CONSTRUCTOR (y is new) IntBox z(7); // regular constructor z = x; // ASSIGNMENT operator (z exists)
x data: 42 copy ctor y data: 42 z (before) data: 7 operator= z (after) data: 42 Summary copy ctor: 1 call operator=: 1 call regular ctor: 2 calls

The Self-Assignment Guard

What happens if someone writes x = x? Without the self-assignment check, operator= would delete x's own data, then try to copy from it: reading freed memory.

IntBox& operator=(const IntBox& other) { if (this != &other) { // guard against x = x delete data; data = new int(*other.data); } return *this; }

The Rule of Three

If your class needs a custom version of any one of these three, it almost certainly needs all three:

Destructor
Frees resources when the object is destroyed: ~MyClass()
Copy Constructor
Deep-copies resources into a new object: MyClass(const MyClass&)
Assignment Operator
Deep-copies resources into an existing object: operator=(const MyClass&)

Common Mistakes

✕ Forgetting Self-Assignment
Writing operator= without if (this != &other) causes undefined behavior on x = x.
✕ Pass by Value in Copy Ctor
Using MyClass(MyClass other) instead of a reference triggers infinite recursion: the parameter copy calls the copy constructor endlessly.
✕ Not Returning *this
If operator= returns void, chained assignment like a = b = c will fail to compile or behave incorrectly.

Copy Constructor vs Assignment

Copy Constructor Assignment Operator
When it fires Object is being created Object already exists
Syntax trigger MyClass b = a; b = a;
Return type None (constructor) MyClass&
Self-assignment check Not needed Required
Free old memory? No (nothing to free) Yes
Part of Rule of Three? Yes Yes

Question 1 of 5

Given: MyClass a; MyClass b = a;
Which special member function is called to create b?

Question 2 of 5

Why must the copy constructor's parameter be a const reference rather than passed by value?

Question 3 of 5

What does the self-assignment check in operator= protect against?

Question 4 of 5

The Rule of Three states that if you define any one of three special functions, you should define all three. Which set is correct?

Question 5 of 5

Consider: MyClass a(10); MyClass b(20); b = a;
What must operator= do with b's old data before copying a's data?