C++
Beginner
1 min read
Constructors, Destructors, and the Rule of Three
Example
#include <iostream>
#include <cstring> // std::strlen, std::strcpy
class MyString {
public:
// Parameterised constructor
explicit MyString(const char* s = "") {
len_ = std::strlen(s);
data_ = new char[len_ + 1];
std::strcpy(data_, s);
std::cout << "Constructed: " << data_ << "\n";
}
// Copy constructor (deep copy)
MyString(const MyString& other) {
len_ = other.len_;
data_ = new char[len_ + 1];
std::strcpy(data_, other.data_);
std::cout << "Copy-constructed: " << data_ << "\n";
}
// Copy-assignment operator
MyString& operator=(const MyString& other) {
if (this == &other) return *this; // self-assignment guard
delete[] data_;
len_ = other.len_;
data_ = new char[len_ + 1];
std::strcpy(data_, other.data_);
std::cout << "Assigned: " << data_ << "\n";
return *this;
}
// Destructor — frees heap memory
~MyString() {
std::cout << "Destroyed: " << data_ << "\n";
delete[] data_;
}
const char* c_str() const { return data_; }
private:
char* data_;
std::size_t len_;
};
int main() {
MyString a("hello");
MyString b = a; // copy constructor
MyString c("world");
c = a; // copy-assignment
return 0;
}