CS 340 - 2/14/13 Assignment vs. Initialization The assignment operator typically executes a superset of code from the initialization code (i.e. the copy constructor) Generics in Java or Templating in C++ template X getMax (X a, X b) { if (a < b) return b; else return a; } template X getMax (X a[], int size) { X temp = a[0]; for (int i = 1 ; i < size; ++i) { if (temp < a[i] ) temp = a[i]; } return temp; } // operator[] // myString str1; // cout << str1[3]; char MyString::operator[] (int index) const { if (index >= 0 && index < length_) return str_[index]; else { cerr << "Error: subscript out of range: " << index << endl; return '\0'; } } // str1[0] = 'J'; char& MyString::operator[] (int index) { if (index >= 0 && index < length_) return str_[index]; else { cerr << "Error: subscript out of range: " << index << endl; return str_[0]; // exceptions are almost needed } } // str1 = "Hello"; // str1[2] = '\0'; // Warning the above allows the object to enter // an invalid data state based on the definition // of the object based on the Object Oriented // development // Concatenation operator+ (not append!!) // str1 = str2 + str3; // attempt #1 - works but has an extra allocation // and deallocation MyString MyString::operator+ (const MyString& rhs) const { MyString temp; temp.length_ = strlen (str_) + strlen(rhs.str_); delete [] temp.str_; temp.str_ = new char[temp.length_ + 1]; strcpy (temp.str_, str_); strcat (temp.str_, rhs.str_ ); return temp; } // attempt #2 MyString MyString::operator+ (const MyString& rhs) const { int tlength = strlen (str_) + strlen(rhs.str_); MyString temp(tlength); strcpy (temp.str_, str_); strcat (temp.str_, rhs.str_ ); return temp; } // The above code replies on the following constructor // this constructor was defined as PRIVATE since // it leaves the object in an invalid state that // must be resolved immediately after the call. MyString::MyString (int len) : str_ (new char [len + 1]), length_ (len) { }