< Previous | Contents | Next >

Returning a Reference

Before you can return a reference from a function, you must specify that youre returning one. Thats what I do in the refToElement() function header.

string& refToElement(vector<string>& inventory, int i)

Returning References 201


By using the reference operator in string& when I specify the return type, Im saying that the function will return a reference to a string object (not a string object itself). You can use the reference operator like I did to specify that a function returns a reference to an object of a particular type. Simply put the reference operator after the type name.

The body of the function refToElement() contains only one statement, which returns a reference to the element at position i in the vector.

return vec[i];

Notice that theres nothing in the return statement to indicate that the function returns a reference. The function header and prototype determine whether a function returns an object or a reference to an object.


Tra p

image

Although returning a reference can be an efficient way to send information back to a calling function, you have to be careful not to return a reference to an out-of-scope object—an object that ceases to exist. For example, the following function returns a reference to a string object that no longer exists after the function ends—and that’s illegal.

string& badReference()

{

string local = "This string will cease to exist once the function ends."; return local;

}

One way to avoid this type of problem is to never return a reference to a local variable.

image