Question on structure in cpp | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 2

Question on structure in cpp

in the function definition below Distance &sum(Distance l1, Distance l2) what does & do in it. if it is call be reference it should be &l1,&l2 why it is &sum Note Distance is a structure. plz help

7th Dec 2017, 9:04 AM
Gamer
Gamer - avatar
5 Respuestas
+ 2
It's not &sum, it's Distance&. It means return Distance by reference. The l1 and l2 are still taken by copy. Be aware that this can easily lead to undefined behaviour if you don't know what you're doing. For example you could construct a Distance on the stack inside sum and return that, because the returned value would be destroyed by the time it returned it's undefined behaviour.
7th Dec 2017, 9:31 AM
Dennis
Dennis - avatar
+ 2
Well, take a function like swap( int& a, int& b ) a call by reference. Which takes the memory address of the variables passed to it and is then able to modify them. So the variables used when calling the function are the same as those used inside the function. This modification is then reflected outside the function because they ( the variables used when calling the function ) share the same memory address. If this was a call by value then an entirely new int would be constructed in memory, resulting in a different memory address. So now the variables used to call the function are different from the ones used inside the function. The function would then edit this different memory and the change wouldn't be reflected outside the function. Returning a reference from a function works the exact same way.
7th Dec 2017, 9:47 AM
Dennis
Dennis - avatar
+ 1
I didn't understand plz explain in detail
7th Dec 2017, 9:33 AM
Gamer
Gamer - avatar
+ 1
Which part don't you understand? The reference part or the undefined behaviour part?
7th Dec 2017, 9:35 AM
Dennis
Dennis - avatar
+ 1
reference part
7th Dec 2017, 9:36 AM
Gamer
Gamer - avatar