// 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. #include #include using namespace std; class combo { public: combo(int initValue = 0, string initText = "foo") { value = initValue; text = initText; cout << "in main constructor" << endl; } int get_value() const { return value; } const string & get_text() const { return text; } // rule of three: copy constructor, assignment, destructor combo(const combo & rhs) { value = rhs.value; text = rhs.text; cout << "in copy constructor" << endl; } ~combo() { cout << "in destructor" << endl; } combo & operator=(const combo & rhs) { if (this != &rhs) { value = rhs.value; text = rhs.text; } cout << "in assignment operator" << endl; return *this; } private: int value; string text; }; int main() { string * s = new string("hello"); cout << "s = " << *s << " of length " << (*s).size() << endl; // the previous line of code can also be done using the arrow operator -> cout << "s = " << *s << " of length " << s->size() << endl; string * t = s; // setting up a second pointer to the string delete s; // without this we didn't pass valgrind // delete t; // double delete would lead to segmentation fault 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; }