Advanced Inheritance 589
16
143: {
144: unsigned short rhsLen = rhs.GetLen();
145: unsigned short totalLen = itsLen + rhsLen;
146: String temp(totalLen);
147: int i, j;
148: for (i = 0; i<itsLen; i++)
149: temp[i] = itsString[i];
150: for (j = 0, i = 0; j<rhs.GetLen(); j++, i++)
151: temp[i] = rhs[i-itsLen];
152: temp[totalLen]=’\0’;
153: *this = temp;
154: }
155:
156: // int String::ConstructorCount =
157: ostream& operator<< ( ostream& theStream,String& theString)
158: {
159: theStream << theString.itsString;
160: return theStream;
161: }
162:
163: int main()
164: {
165: String theString(“Hello world.”);
166: cout << theString;
167: return 0;
168: }
Hello world.
On lines 21–22,operator<<is declared to be a friend function that takes an
ostreamreference and a Stringreference and then returns an ostreamreference.
Note that this is not a member function of String. It returns a reference to an ostreamso
that you can concatenate calls to operator<<, such as this:
cout << “myAge: “ << itsAge << “ years.”;
The implementation of this friendfunction is on lines 157–161. All this really does is
hide the implementation details of feeding the string to the ostream, and that is just as it
should be. You’ll see more about overloading this operator and operator>>on Day 17.
Summary ..............................................................................................................
Today, you saw how to delegate functionality to an aggregated object. You also saw how
to implement one class in terms of another by using either aggregation or private inheri-
tance. Aggregation is restricted in that the new class does not have access to the pro-
tected members of the aggregated class, and it cannot override the member functions of
OUTPUT
ANALYSIS
LISTING16.9 continued