Can any one explain to me the difference between these two functions?
The first example may yield undefined behavior because the returned reference "points" to a variable that, at the end of the function, gets destroyed. This is very similar (almost identical) to the definition of dangling pointer.
The second case is the normal, "correct" way of returning the variable in the example specified above.
and tell me what the purpose when we use '&' operator after return type of a function?
The purpose of a &
after a type in the return statement is to return a reference to that type.
When should we use it because I've rarely seen it before.
Generally, passing a reference or returning a reference is useful to avoid making a copy of the parameter being passed/returned, which may be costly.
Since C++11 there's a better way of handling returning big objects: move semantics.
In other cases it is used to provide access to internal members of a class. This is the example of std::string::operator[]
for example:
char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
It may also be used to allow function call chains. This is the case of:
std::cout << 'H' << 'e' << 'l' << 'l' << 'o';
for example. In the code above, the std::ostream::operator<<
returns a reference to itself.