In C++,
function() = 10;
Works if function returns a variable by reference, right?
Would someone please elaborate on this in detail?
Consider this piece of code first
int *function();
...
*function() = 10;
Looks similar, isn't it? In this example, function
returns a pointer to int
, and you can use it in the above way by applying a unary *
operator to it.
Now, in this particular context you can think of references as "pointers in disguise". I.e. reference is a "pointer", except that you don't need to apply the *
operator to it
int &function();
...
function() = 10;
In general, it is not a very good idea to equate references to pointers, but for this particular explanation it works very well.
Consider the following code, MyFunction returns a pointer to an int, and you set a value to the int.
int *i;
i = MyFunction();
*i = 10;
Are you with me so far?
Now shorten that to
*(MyFunction()) = 10;
It does exactly the same thing as the first code block.
You can look at a reference as just a pointer that's always dereferenced. So if my function returned a reference - not a pointer - to an int the frist code block would become
int &i;
i = MyFunction();
i = 10;
and the second would become
MyFunction() = 10;
You still with me?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With