Rule of Three — if you need one of destructor, copy constructor, or copy assignment, you likely need all three.
1class MyClass {2private:3 int* data;45public:6 // Constructor7 MyClass(int value) {8 data = new int(value);9 }1011 // Destructor12 ~MyClass() {13 delete data;14 }1516 // Copy constructor17 MyClass(const MyClass& other) {18 data = new int(*other.data);19 }2021 // Copy assignment22 MyClass& operator=(const MyClass& other) {23 if (this != &other) {24 *data = *other.data;25 }26 return *this;27 }28};
Why needed: