I’m trying to understand how this type of function works and how you would use it.
I assume there’s some class we’ll call it test.
class Test {
}
I saw this type of function in a header file and I’m trying to figure out what it does. And how to use it properly.
Test& testFunction();
Appreciate the help.
What’s in front of the function name is the type that the function will return. In this case,
testFunctionis returning aTestobject. The&in this case (reference) means that it will return aTest-reference. This is important if you wish to modify the returned object when you call the function. Or use it in some way not possible with “return-by-value”.Your code doesn’t tell us much about what you’re going to be doing with the return value, but here is a good example that’s used quite commonly:
*thishere is the actual object on which its method.fis being called. What’s special here is that since we are returning a reference, we can chain calls while maintaining the original object.*thiswill be the same*thisevery time. With return-by-value we aren’t able to do this. For example:By reference:
By value:
tis changed only once because the object is lost on the next call.