DeveloperBreeze

Rule Of Five Development Tutorials, Guides & Insights

Unlock 1+ expert-curated rule of five tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your rule of five skills on DeveloperBreeze.

Deep Copy in C++: How to Avoid Shallow Copy Pitfalls

Tutorial April 11, 2025

A deep copy duplicates the actual data pointed to, not just the pointer.

class Deep {
public:
    int* data;

    Deep(int val) {
        data = new int(val);
    }

    // Copy constructor for deep copy
    Deep(const Deep& other) {
        data = new int(*other.data);
    }

    // Assignment operator for deep copy
    Deep& operator=(const Deep& other) {
        if (this != &other) {
            delete data;
            data = new int(*other.data);
        }
        return *this;
    }

    ~Deep() {
        delete data;
    }
};