// MT1Q2.cpp - Assignment and destructor #include #include class X { public: X() { pStr = new std::string("default x"); std::cout << "\n X constructed"; } X(const X& x) { pStr = new std::string(*(x.pStr)); std::cout << "\n X copied"; } ~X() { delete pStr; std::cout << "\n X destroyed"; } void take(std::string str) { delete pStr; pStr = new std::string(str); } const std::string say() { return *pStr; } X& operator=(const X& x) { if(&x == this) return *this; delete pStr; pStr = new std::string(*(x.pStr)); std::cout << "\n X assigned"; } private: std::string* pStr; }; class Y { public: // X has correct copy, assignment, and destruction // semantics so compiler generated operations for Y // will be correct Y() { std::cout << "\n default contruction of Y"; } Y(const X& client_x) : x(client_x) { std::cout << "\n Y constructed"; } std::string say() { return x.say(); } private: X x; }; int main() { X x; x.take("a string from client"); Y y1(x); std::cout << "\n " << y1.say(); Y y2 = Y(); std::cout << "\n " << y2.say() << "\n\n"; return 0; }