// MT2Q4.cpp - build and destroy #include #include class B { public: B() : pStr(new std::string("default")) { std::cout << "\n B constructed"; } B(const B& b) : pStr(new std::string(*(b.pStr))) { std::cout << "\n B copied"; } virtual ~B() { delete pStr; std::cout << "\n B destroyed"; } void take(std::string str) { delete pStr; pStr = new std::string(str); } virtual const std::string say() { return *pStr; } B& operator=(const B& b) { if(&b == this) return *this; delete pStr; pStr = new std::string(*(b.pStr)); std::cout << "\n B assigned"; } private: std::string* pStr; }; class D : public B { public: // B has correct copy, assignment, and destruction // semantics so compiler generated operations for D // will be correct virtual const std::string say() { std::string temp = "from derived class: "; return temp + static_cast(this)->B::say(); } }; int main() { B b; b.take("a string from client"); std::cout << "\n " << b.say(); D d1; d1.take("another string from client"); std::cout << "\n " << d1.say(); D d2 = D(); std::cout << "\n " << d2.say() << "\n\n"; return 0; }