/* This program motivates why you would want to redefine the copy constructor and assignment overload. In this program, we have a class with a string and a pointer to that string. When we don't redefine the copy constructor and the assignment overlead, the pointer inside the class is incorrect when we copy or assign an instance of the class. This leads to confusion, and in some cases, bugs. */ #include #include using namespace std; class Person { public: Person(); void Set(const string &s); void Print_From_String() const; void Print_From_Pointer() const; protected: string name; string *ptr; }; /* The constructor sets the pointer to NULL. The string is already empty. */ Person::Person() { ptr = NULL; } /* Set() sets the string and the pointer. */ void Person::Set(const string &s) { name = s; ptr = &name; } /* Print the name from the string. */ void Person::Print_From_String() const { cout << name << endl; } /* Print the name from the pointer. */ void Person::Print_From_Pointer() const { if (ptr != NULL) cout << *ptr << endl; } int main() { Person c1, c2; vector v; c1.Set("Jim"); c2 = c1; v.resize(2, c1); c1.Set("Plank"); printf("Printing c1 from string and pointer:\n"); c1.Print_From_String(); c1.Print_From_Pointer(); printf("\n"); printf("Printing c2 from string and pointer:\n"); c2.Print_From_String(); c2.Print_From_Pointer(); printf("\n"); printf("Printing v[0] from string and pointer:\n"); v[0].Print_From_String(); v[0].Print_From_Pointer(); return 0; }