CS 340 - 2/12/13 Happy Birthday Abe // Copy Constructor for MyString MyString::MyString (const MyString& pStr) : str_ ( new char [pStr.length_ + 1]), length_ ( pStr.length_ ) { strcpy ( str_, pStr.str_ ); } // Use of assignment operator to produce a // deep copy // MyString s1, s2, s3; // s1 = s2; // s1.operator= (s2); // s1 = s2 = s3; // s1.operator= ( s2.operator= (s3) ); // s1 = (An Instance of MyString); // s1 = s1; MyString& MyString::operator= (const MyString &rhs) { // Step 1 - makes sure this is not the same instance // as rhs if (this == &rhs) return *this; // Step 2 - deallocate existing dynamic memory // often mimics the destructor code delete [] str_; // step 3 - set up the copy // often mimics the Copy Constructor code str_ = new char [ rhs.length_ + 1 ]; length_ = rhs.length_; strcpy (str_ , rhs.str_ ); // step 4 - return the this pointer by reference return *this; }