maintain their ‘life’ throughout this process and so there is no object copying involved. Therefore, the parameter passed must be passed by reference and the value returned must also be returned by reference.
Pass-through objects are especially useful in ‘chained’ use of operators or functions. Another example is shown below where a, b, and c are integer objects:
a = b = c = 3;
Once again, the precedence of operations can be shown using parentheses:
(a = (b = (c = 3)));
After the first assignment operation the expression reduces to:
(a = (b = (c));
Therefore, in the operation c = 3, c enters as a parameter and then appears as the return value, explaining why c = 3 can be replaced by c.
An analogy from day-to-day life can be used to further explain the use of returning values by reference. Consider a situation where you have a string and a set of beads. We want to thread all the beads, one at a time, onto the string. We will write a function to receive the string and a bead. The purpose of the function is to attach one bead to the string and to return the same string with the beads(s) it received.
We specify that a function must return a value by reference by adding & after the return value type in the function heading. This is shown in bold typeface in the Add_a_Bead function shown below:
String& Add_A_Bead(String& string, Bead bead)
{
string = string + bead; return string;
}
For the two parameters of the function Add_A_Bead(), parameter string is of data type String and bead is of data type Bead. The expression string = string + bead represents attaching a bead to the string. You can attach n beads to the same string by executing this function n times.
If we did not return the value by reference, each time you execute the function to attach a bead, you will get a new copy of the string, with an increasing number of beads on each subsequent copy. If you execute such a function n times, you will create and discard n copies of the string, the first copy having one bead, the second copy having 2 beads etc. until you end up with the last copy having n beads - what a waste of time and memory! In addition, you do not have the original string - you have a copy.