- example: string class class String { public: String(const char s[]=""); String(const String & s1); ~String(); private: char * info; }; String :: String (const char s[]) { info = new char[strlen(s)+1]; strcpy(info, s); } String :: String (const String & s1) { info = new char[strlen(s1.info)+1]; strcpy(info, s1.info); } String :: ~String () { delete [] info; } String:: String & operator = (const String & rhs) { if (this != &rhs) { // cover s=s case delete [] info; info = new char[strlen(rhs.info)+1]; strcpy(info, rhs.info); } return *this; } String:: String & operator += (const String & rhs) { char * temp = new char[strlen(info) + strlen(rhs.info) + 1]; strcpy(temp, info); strcat(temp, rhs.info); delete [] info; info = temp; return *this; } String operator + (const String & s, const String & t) // friend { String temp(s); // use copy constructor temp += t; // use class += operator return temp; // local ok bc return by value only } // note this function created a new temporary string object, will be deleted // when temporary copy isn't needed anymore. // eg: // String s("hello"), t; // t = s + " world"; // constructor called for world String:: char & operator[] (int i) // can be on left side of assignment { return info[i]; } // String S("hello"); S[1]='a'; String:: char operator[] (int i) const; // for constant string objects { return info[i]; } // const String myname("Joanne"); cout << myname[4]; String:: const char* charString() const; // type converter { return info; } ostream & operator << (ostream & out, const String & s) // friend { out << s.charString(); } bool operator == (const String & s, const String & t) // friend { return strcmp(s.info, t.info) == 0; } bool operator < (const String & s, const String & t) // friend { return strcmp(s.info, t.info) < 0; } bool operator >= (const String & s, const String & t) { return strcmp(s.info, t.info) >= 0; }