// 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 initial_value = 0, const string & initial_text = "foo") { value = initial_value; text = new string(initial_text); cout << "in main constructor" << endl; } combo(const combo & rhs) { value = rhs.value; // default is shallow copy: text = rhs.text 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; // default is shallow copy: text = rhs.text // We could delete the old string and make a new one, as in: // delete text; // text = new string(*rhs.text); // We can also just let the string object do the copying *text = *rhs.text; } cout << "in assignment operator" << endl; return *this; } int get_value() const { return value; } const string & get_text() const { return *text; } private: int value; string * text; }; int main() { /* string * s = new string("hello there"); cout << "s = " << *s << " with length " << (*s).size() << endl; cout << "s = " << *s << " with length " << s->size() << endl; string * t = s; delete s; delete t; */ combo c1(23, "bar"); combo c2(71); combo c3; cout << "c1: " << c1.get_text() << " " << c1.get_value() << endl; cout << "c2: " << c2.get_text() << " " << c2.get_value() << endl; cout << "c3: " << c3.get_text() << " " << c3.get_value() << endl; cout << "before inner scope" << endl; { combo c(12); } cout << "after inner scope" << endl; combo c4 = c1; // combo c4(c1); cout << "c4: " << c4.get_text() << " " << c4.get_value() << endl; combo c5; c5 = c2; return 0; }