// sample program with some examples of dynamic allocation in main and a class // for storing a combination of an int and a string with a regular constructor, // a copy constructor, a destructor, and an overridden assignment operator. // Each of these produces output indicating that they are being executed. // exploring rule of 3: destructor, copy constructor, assignment operator // this combo class has the default versions of the "rule of 3" elements that // are provided for free by C++ #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 regular constructor" << endl; } combo(const combo & rhs) { value = rhs.value; text = rhs.text; cout << "in copy constructor" << endl; } ~combo() { cout << "in destructor for value " << value << endl; } combo & operator=(const combo & rhs) { value = rhs.value; 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; }