Search⌘ K
AI Features

Solution: The Rule of Three

Explore the Rule of Three in C++ to understand how constructors, destructors, and copy constructors work together for safe memory management. Learn to implement deep copies and resource cleanup to avoid leaks and ensure correct object behavior.

We'll cover the following...
C++ 23
#include <iostream>
class HeapInt {
private:
int* ptr;
public:
// Constructor: Acquires resource (RAII)
HeapInt(int value) {
ptr = new int(value);
}
// Destructor: Releases resource
~HeapInt() {
delete ptr;
}
// Copy constructor: Performs deep copy
HeapInt(const HeapInt& other) {
// Allocate new memory, then copy the value
ptr = new int(*(other.ptr));
}
// Operator overloading
bool operator==(const HeapInt& other) {
// Compare the values inside, not the memory addresses
return *ptr == *(other.ptr);
}
int getValue() const { return *ptr; }
};
int main() {
HeapInt a(10);
HeapInt b = a; // Calls copy constructor
HeapInt c(20);
if (a == b) std::cout << "a and b are equal (Deep Copy worked!)\n";
else std::cout << "a and b are different\n";
if (a == c) std::cout << "a and c are equal\n";
else std::cout << "a and c are different\n";
return 0;
}
...