Consider a simple class that wraps an array solely for the purpose of providing an example of what the OP can do with a returned reference.
class example
{
private:
int array[]= {1,2,3,4,5,6,7,8,9,0};
public:
int get(int index)
{
return array[index];
}
int & get2(int index)
{
return array[index];
}
}
Now we have an example that will not go into the badlands of undefined behaviour and can show you the power of this fully armed and operational reference.
Say we have
example x;
We can call either get function to retrieve a value
int val1 = x.get(1);
int val2 = x.get2(2)
but we can also
x.get2(3) = 30;
because get2 returns a reference we can assign to it and make the assignment stick.
This is invaluable should you want to add an index operator to example
int & operator[](int index)
{
return array[index];
}
because it allows the expected array behaviour
int val = x[5];
x[6] = 10;
EDIT
Tony D brings up another important feature. Returning a reference returns by reference. In addition to allowing modification of the returned object, this does not make a copy and saves whatever effort would have been consumed by making a copy. For the example case of integers this is moot. The cost of passing an integer and a reference to an integer will either be the same or so close that it shouldn't matter. This is not true of a larger, more complex object that could take a significant amount of effort to copy or an object that cannot or should not be copied.
BigFreakingObject & getBigFreakingObject();
will allow the caller to operate on a BigFreakingObject
without incurring the costs of duplicating it. This hands over the keys to the kingdom however and allows the caller to do to BigFreakingObject
whatever BigFreakingObject
's permissions will allow, and this may conflict with the requirements of BigFreakingObject
's owner.
Declaring the reference as const
with
const BigFreakingObject & getBigFreakingObject();
or
BigFreakingObject const & getBigFreakingObject();
will provide a reference to a BigFreakingObject
but not allow the caller to modify its state, protecting the owner of BigFreakingObject
from any unpleasant surprises.
For more details on this, read up on Const Correctness.