Answer the question
In order to leave comments, you need to log in
What is the purpose of returning a value by reference?
I used to think that returning a value by reference differs from returning a value by a pointer in that in the first case it would not be necessary to dereference the pointer, but apparently this is not so. I wrote this example:
#include <iostream>
int& func(int &a)
{
std::cout << &a << "\n\n";
return a;
}
int main()
{
int a;
int b;
b = func(a);
std::cout << &b << "\n\n";
std::cout << &a << "\n\n";
return 0;
}
Answer the question
In order to leave comments, you need to log in
b = func(a);
This is where you took the reference returned by func and copied the value into b. So the &b below will give you the address of the variable b, not what you wanted.
Returning references is convenient when you need to return a value without copying and it always exists. Because a function that returns a pointer can, in general, return nullptr as well. On mind, it would be necessary to check this pointer before dereferencing. But links - they always point somewhere.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question