Advanced Inheritance 583
16
79: }
80:
81: // destructor, frees allocated memory
82: String::~String ()
83: {
84: delete [] itsString;
85: itsLen = 0;
86: // cout << “\tString destructor” << endl;
87: }
88:
89: // operator equals, frees existing memory
90: // then copies string and size
91: String& String::operator=(const String & rhs)
92: {
93: if (this == &rhs)
94: return *this;
95: delete [] itsString;
96: itsLen=rhs.GetLen();
97: itsString = new char[itsLen+1];
98: for (int i = 0; i<itsLen;i++)
99: itsString[i] = rhs[i];
100: itsString[itsLen] = ‘\0’;
101: return *this;
102: // cout << “\tString operator=” << endl;
103: }
104:
105: //non constant offset operator, returns
106: // reference to character so it can be
107: // changed!
108: char & String::operator[](int offset)
109: {
110: if (offset > itsLen)
111: return itsString[itsLen-1];
112: else
113: return itsString[offset];
114: }
115:
116: // constant offset operator for use
117: // on const objects (see copy constructor!)
118: char String::operator[](int offset) const
119: {
120: if (offset > itsLen)
121: return itsString[itsLen-1];
122: else
123: return itsString[offset];
124: }
125:
126: // creates a new string by adding current
127: // string to rhs
128: String String::operator+(const String& rhs)
129: {
130: int totalLen = itsLen + rhs.GetLen();
LISTING16.8 continued