⚙️ C++ Intermediate

What is the difference between shallow copy and deep copy?

Why Interviewers Ask This

This tests whether you can apply C++ knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

When copying an object that contains pointer members, the behavior depends on whether you do a shallow or deep copy: Shallow copy: copies only the pointer value — both objects point to the same underlying data. The compiler-generated copy constructor performs a shallow copy. class ShallowArray { int* data; int size; public: ShallowArray(int s) : data(new int[s]), size(s) {} // Default copy constructor (shallow): // Copies data pointer, not the array // Both original and copy point to same memory! }; ShallowArray a(5); ShallowArray b = a; // Shallow -- b.data == a.data delete[] a.data; // Now b.data is dangling!. Problems: double deletion (undefined behavior when both objects are destroyed), modifying through one object affects the other. Deep copy: allocates new memory and copies the contents: class DeepArray { int* data; int size; public: DeepArray(int s) : size(s), data(new int[s]) {} // Deep copy constructor: DeepArray(const DeepArray& other) : size(other.size), data(new int[other.size]) { std::copy(other.data, other.data + size, data); } // Deep copy assignment: DeepArray& operator=(const DeepArray& other) { if (this != &other) { delete[] data; size = other.size; data = new int[size]; std::copy(other.data, other.data + size, data); } return *this; } ~DeepArray() { delete[] data; } }; DeepArray a(5); DeepArray b = a; // Deep -- separate copy of array. Modern solution: use std::vector<int> instead of raw arrays — its copy constructor performs a deep copy automatically (Rule of Zero). Shallow copy is appropriate when sharing ownership (std::shared_ptr handles this with reference counting).

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex C++ answers easy to follow.