DeveloperBreeze

C++ Pointers Development Tutorials, Guides & Insights

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

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

Tutorial April 11, 2025

class String {
private:
    char* buffer;

public:
    String(const char* str) {
        buffer = new char[strlen(str) + 1];
        strcpy(buffer, str);
    }

    // Copy constructor
    String(const String& other) {
        buffer = new char[strlen(other.buffer) + 1];
        strcpy(buffer, other.buffer);
    }

    // Assignment operator
    String& operator=(const String& other) {
        if (this != &other) {
            delete[] buffer;
            buffer = new char[strlen(other.buffer) + 1];
            strcpy(buffer, other.buffer);
        }
        return *this;
    }

    ~String() {
        delete[] buffer;
    }

    void print() const {
        std::cout << buffer << std::endl;
    }
};
String a("Hello");
String b = a;       // deep copy
String c("World");
c = a;              // deep assignment