Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This is common function that I see.
C++
std::string foo(){}


but not this
C++
std::string &foo(){}


What is the second one.
What the difference in what they do?
I understand that
C++
std::string foo(int &a){}
is passing by reference.
The second foo... it is pass function by reference or what?

What I have tried:

I came across this function on one of my question in quora.
Still didn't understand. So I ask here. Hope anybody can help
Posted
Updated 11-Feb-16 7:05am
v2
Comments
Richard MacCutchan 11-Feb-16 12:42pm    
That will give a syntax error, you cannot return a reference to void. Try a proper type and see what happens.
Are Riff 11-Feb-16 13:04pm    
sorry, it was something else, it was std::string foo()

1 solution

Better read it as
std::string&  foo()
The function returns a reference to a string object instead of a string object.
 
Share this answer
 
Comments
Albert Holguin 12-Feb-16 15:55pm    
This is dangerous though... because scope plays an important part of this. Don't return by reference anything that's going to go out of scope as soon as the function is finished!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900