// new version of the combo class that stores a pointer to a string instead of // a stack-allocated string #include #include using namespace std; class combo { public: combo(int initValue = 0, string initText = "foo") { value = initValue; text = new string(initText); cout << "in main constructor" << endl; } int get_value() const { return value; } const string & get_text() const { return *text; } combo(const combo & rhs) { value = rhs.value; // the next line makes a new string instead of just copying the pointer text = new string(*rhs.text); cout << "in copy constructor" << endl; } ~combo() { delete text; cout << "in destructor" << endl; } combo & operator=(const combo & rhs) { if (this != &rhs) { value = rhs.value; // first we have to delete the string that this currently points to delete text; // then we can allocate a new string with a copy of the text text = new string(*rhs.text); } cout << "in assignment operator" << endl; return *this; } private: int value; string * text; }; int main() { combo c1(14, "bar"); cout << "c1: " << c1.get_value() << " " << c1.get_text() << endl; combo c2(18); cout << "c2: " << c2.get_value() << " " << c2.get_text() << endl; combo c3; cout << "c3: " << c3.get_value() << " " << c3.get_text() << endl; combo c4 = c2; cout << "c4: " << c4.get_value() << " " << c4.get_text() << endl; combo c5; c5 = c1; cout << "c5: " << c5.get_value() << " " << c5.get_text() << endl; return 0; }