Returning by reference

Whats the difference between returning by reference and returning the variable?

Also:

would a getter that returns the reference of a variable allow the calling function to directly modify that variable?

1
2
3
4
5
6
class a_class{

/* .....  */

    int& return_somthing();
};
This might help explain.
http://www.learncpp.com/cpp-tutorial/74a-returning-values-by-value-reference-and-address/

Return by reference

Just like with pass by reference, values returned by reference must be variables (you can not return a reference to a literal or an expression). When a variable is returned by reference, a reference to the variable is passed back to the caller. The caller can then use this reference to continue modifying the variable, which can be useful at times. Return by reference is also fast, which can be useful when returning structs and classes.

However, returning by reference has one additional downside that pass by reference doesn’t — you can not return local variables to the function by reference. Consider the following example:

1
2
3
4
5
int& DoubleValue(int nX)
{
    int nValue = nX * 2;
    return nValue; // return a reference to nValue here
} // nValue goes out of scope here 

See the problem here? The function is trying to return a reference to a value that is going to go out of scope when the function returns. This would mean the caller receives a reference to garbage. Fortunately, your compiler will give you an error if you try to do this.

Return by reference is typically used to return arguments passed by reference to the function back to the caller. In the following example, we return (by reference) an element of an array that was passed to our function by reference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// This struct holds an array of 25 integers
struct FixedArray25
{
    int anValue[25];
};
 
// Returns a reference to the nIndex element of rArray
int& Value(FixedArray25 &rArray, int nIndex)
{
    return rArray.anValue[nIndex];
}
 
int main()
{
    FixedArray25 sMyArray;
 
    // Set the 10th element of sMyArray to the value 5
    Value(sMyArray, 10) = 5;
 
    cout << sMyArray.anValue[10] << endl;
    return 0;
}

This prints:

5
When we call Value(sMyArray, 10), Value() returns a reference to the 10th element of the array inside sMyArray. main() then uses this reference to assign that element the value 5.

Although this is somewhat of a contrived example (because you could access sMyArray.anValue directly), once you learn about classes you will find a lot more uses for returning values by reference.



*edit so yes your answer would be yes.

You can do return_something() = value;
Last edited on
Thanks.
Topic archived. No new replies allowed.