Cpp - Reference Returning References

Introduction

The return type of a function can be a reference type.

The function call then represents an object, and can be used just like an object.

string& message()           // Reference! 
{ 
  static string str ="Today only cold cuts!"; 
  return str; 
} 

This function returns a reference to a static string, str.

The object referenced by the return value must exist after leaving the function.

The function message() is of type "reference to string." Thus, calling

message() 

represents a string type object, and the following statements are valid:

message() = "Let's go to the beer garden!"; 
message() += " Cheers!"; 
cout << "Length: " << message().length(); 

In these examples, a new value is first assigned to the object referenced by the function call.

Then a new string is appended before the length of the referenced string is output in the third statement.

If you want to avoid modifying the referenced object, you can define the function type as a read-only reference.

const string& message();     // Read-only! 

References are commonly used as return types when overloading operators.

Demo

// Demonstrates the use of return values with reference type. 
#include <iostream> 
#include <string> 
using namespace std; 

// Returns a reference to the minimum. 
double& Min( double&, double&);            
int main() /*from   w  w  w . ja  v  a  2  s  .  c  om*/
{ 
   double x1 = 1.1,  x2 = x1 + 0.5,  y; 

   y = Min( x1, x2);        // Assigns the minimum to y. 
   cout << "x1 = " << x1 << "     " 
         << "x2 = " << x2 << endl; 
   cout << "Minimum: " << y  << endl; 

   ++Min( x1, x2);            
   cout << "x1 = " << x1 << "     "      
         << "x2 = " << x2 << endl;       

   Min( x1, x2) = 10.1;            
                                      
   cout << "x1 = " << x1 << "     "   
         << "x2 = " << x2 << endl;    
   Min( x1, x2) += 5.0;            
                                      
   cout << "x1 = " << x1 << "     "   
         << "x2 = " << x2 << endl;    
   return 0; 
} 

double& Min( double& a, double& b){                                    
    return a <= b ? a : b;           
}

Result

The expression Min(x1,x2) represents either the object x1 or the object x2, that is, the object containing the smaller value.

Related Topic