Coupon Accepted Successfully!


Return By Reference

We have studied the reference variable and it’s functioning. A reference allows creating alias for the pre-existing variable. A reference can also be returned by the function. A function that returns reference variable is in fact an alias for referred variable. This technique of returning reference is used to establish cascade of member functions calls in operator overloading. Consider the following example:

The below given program illustrates return by reference.

7.7 Write a program to return a value by reference.

Explanation: In the above program, the statement int & min (int &j, int &k) declares prototype of function min(). The ‘&’ reference operator is used because the function returns reference to int and also receives arguments as reference. The function min() receives two integers as reference and returns minimum value out of two by reference.

7.8 Write a program to demonstrate return by reference.

Explanation: In function main(), the statement large (l, k) = 120 calls the function large(). It returns reference to the variable containing larger value and assigns the value 120 to it. The return type of function large() is int ‘&’ (reference), it indicates that the call to function large() can be written on the left side of the assignment operator. Consequently, the statement large(l,k) = 120 is legal and assigns 120 to the variable containing larger value.

Test Your Skills Now!
Take a Quiz now
Reviewer Name