๐ Date: Feb 16, 2026
๐ง Mood: Genetic Engineer ๐งฌ
๐ฅ Topic: OOPs Part 4: Copy Constructor (Shallow vs Deep)
๐ฏ Cloning an Object
Imagine you have a Hero object named "Superman" with 100 HP.
Now you want to create another hero "Clone_Superman" with the exact same stats.
Instead of setting values manually again, we can Copy the first object. This is where the Copy Constructor comes in.
Hero h1(100); // Original Hero h2 = h1; // Copy Created! (Copy Constructor Called)
⚠️ The Trap: Shallow vs Deep Copy
This is the most asked Interview Question in OOPs.
1. Shallow Copy (The Default)
Imagine Student A has a Notebook. Student B wants to copy. In Shallow Copy, Student B doesn't buy a new notebook. He just holds Student A's notebook.
❌ The Problem: If Student A tears a page, Student B's page is also gone! (Because they share the same memory address).
2. Deep Copy (The Solution)
Student B buys a New Notebook and writes everything down from Student A's notebook.
✅ The Benefit: If Student A tears a page, Student B is safe. They have separate memory.
๐ป Defining a Copy Constructor
By default, C++ does a Shallow Copy. If you want Deep Copy (usually when using Pointers), you have to write your own Copy Constructor.
class Hero {
public:
int health;
int level;
// 1. Simple Constructor
Hero(int h, int l) {
health = h;
level = l;
}
// 2. Custom COPY Constructor
// Syntax: ClassName(const ClassName &obj)
Hero(const Hero &temp) {
cout << "⚙️ Copy Constructor Called!" << endl;
this->health = temp.health;
this->level = temp.level;
}
void print() {
cout << "Health: " << health << " Level: " << level << endl;
}
};
int main() {
Hero h1(100, 5);
h1.print();
// Copying h1 to h2
Hero h2(h1);
// OR: Hero h2 = h1;
h2.print(); // Prints same values as h1
return 0;
}
๐ก Why pass by Reference `&temp`?
If we pass by value Hero temp, it will create a copy. To create a copy, it will call Copy Constructor again. This will create an Infinite Loop! That's why we always pass by Reference &.
๐ Day 47 Challenge
- Create a class
Bookwithpages. - Create an object
b1with 500 pages. - Create
b2by copyingb1. - Print "Book Copied Successfully!".
- Bonus: Try to remove
&from the copy constructor arguments and see the error.
Next Up: Day 48 - Inheritance (The Family Tree of Code).
No comments:
Post a Comment