/* In this program, we redefine the copy constructor and the assignment overlead so that these operations set the pointer correctly. */ #include #include using namespace std; class Person { public: Person(); Person(const Person &p); Person& operator= (const Person &p); 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; } /* The copy constructor sets the name and the pointer. */ Person::Person(const Person &p) { Set(p.name); } /* The assignment overload also sets the name and the pointer. */ Person& Person::operator= (const Person &p) { Set(p.name); return *this; } /* 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; }