Home

C++ Examples: Returning a Reference

As a function can be created to return a value of a primitive type, a function can also be defined to return a reference to a primitive type. When declaring such a function, you must indicate that it is returning a reference by preceding it with the & operator. Here is an example:

double & GetWeeklyHours()
{

}

In the body of the function, defined the desired behavior of the function as you see fit. The most important rule to apply is that the function must return not only a reference but a reference to the appropriate type. When returning the value, don't precede the name of the variable with &. Here is an example:

double & GetWeeklyHours()
{
    double h = 46.50;

    double &hours = h;

    return hours;

}

When calling a function that returns a reference, you can proceed as if it returns a regular value but of the appropriate type. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
using namespace std;

double & GetWeeklyHours()
{
    double h = 46.50;

    double &hours = h;

    return hours;
}
//---------------------------------------------------------------------------
int main()
{
    double hours = GetWeeklyHours();

    cout << "Weekly Hours: " << hours << endl;

    return 0;
}

//---------------------------------------------------------------------------

This would produce:

Weekly Hours: 46.5
 

Home Copyright © 2006-2016, FunctionX, Inc.