< Previous | Contents | Next >
Before you can return a reference from a function, you must specify that you’re returning one. That’s what I do in the refToElement() function header.
string& refToElement(vector<string>& inventory, int i)
By using the reference operator in string& when I specify the return type, I’m 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 there’s 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
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.