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=() ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.