DeveloperBreeze

Rule Of Three Development Tutorials, Guides & Insights

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

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

Tutorial April 11, 2025

You must implement all three. This is called the Rule of Three.

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;
    }
};