Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#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_ << " "; } // 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_ << " "; } // 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_ << " "; return *this; } // Destructor — frees heap memory ~MyString() { std::cout << "Destroyed: " << data_ << " "; 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; }
Result
Open