Real life example
Shallow copy = dost ko apne ghar ki chaabi di (ek hi ghar). Deep copy = uske liye naya ghar bana diya.
Industry example
Image buffer class: shallow copy se dono delete karein to crash (double free). Deep copy safe hai.
C++ code
Buf(const Buf& o){
n = o.n; p = new int[n];
for(int i=0;i<n;i++) p[i] = o.p[i]; // deep
}
~Buf(){ delete[] p; }
What happens when it runs
b2 = b1 (deep) Alag memory. b1 delete hua to b2 safe.
Run the full program in the compiler Interactive version
Quiz
Pointer wali class me default copy kya karti hai?
Default copy sirf address copy karti hai (shallow). Deep copy khud likhni padti hai.
Try it yourself
Write one example of Copy Constructor, Destructor, this from your own home, school or work. Then change the program in the compiler and run it again.
All 12 OOP lectures
- Lecture 1: Introduction aur Objects
- Lecture 2: Encapsulation aur Interface
- Lecture 3: Abstraction, Class, Inheritance
- Lecture 4: Inheritance ke Concepts
- Lecture 5: Association, Composition, Aggregation
- Lecture 6: Polymorphism
- Lecture 7: C++ me Class
- Lecture 8: Constructor
- Lecture 9: Copy Constructor, Destructor, this
- Lecture 10: this Pointer aur const Functions
- Lecture 11: const, Initializer List, static
- Lecture 12: static Functions aur Array of Objects
START WELL TO END WELL