foo(int &bar)
{
bar = 5;
}
The call to this function would be
int foobar = 2;
foo(foobar);
Am I right in thinking that the function parameter essentially ‘gets’ the memory address of the variable, but does not then have to be dereferenced in foo, and that I would be changing the original value of foobar? Before this I was under the Impression that you would have to pass in a memory address like this:
foo(&foobar);
and then use the variable inside foo like this:
*bar = 5;
Am I right in thinking that this is wrong? I think, like a lot of beginners, the confusion came from thinking that a reference was like a pointer in that it held a memory address, but it’s never really a type is it? Just an operator.
References are usually implemented with underlying pointers (although that is not mandated by the standard), but they are a totally different beast than pointers. A reference is simply a new name or alias for an existing variable. When you do
you are invoking
footo be evaluated with the variablefoobar, so essentiallybarwithinfoobecamesfoobar. The usual compiler impementation for this is to actually implement this code like this: