Returning a Reference to a Non-const Object

Two common examples of returning a non-const object are overloading the assignment operator and overloading the << operator for use with cout. The first is done for reasons of efficiency, and the second for reasons of necessity.

The return value of operator=() is used for chained assignment:

String s1("Good stuff");
String s2, s3;
s3 = s2 = s1;

In this code, the return value of s2.operator=(s1) is assigned to s3. Returning either a String object or a reference to a String object would work, but, as with the Vector example, using a reference allows the function to avoid calling the String copy constructor to create a new String object. In this case, the return type is not const because the operator=() method returns a reference to s2, which it does modify.

The return value of operator<<() is used for chained output:

String s1("Good stuff");
cout << s1 << "is coming!";

Here, the return value of operator<<(cout, s1) becomes the object used to display the string "is coming!". Here, the return type has to be ostream & and not just ostream. Using an ostream return type would require calling the ostream copy constructor, and, as it turns out, the ostream class does not have a public copy constructor. Fortunately, returning a reference to cout poses no problems because cout is already in scope in the calling function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.74.66