1
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.

Dollarslice
  • 9,917
  • 22
  • 59
  • 87
  • `foo(&bar){}` is not a proper C++ function definition. – K-ballo Oct 06 '11 at 17:06
  • exact dup of http://stackoverflow.com/questions/620604/difference-between-a-pointer-and-reference-parameter? – N_A Oct 06 '11 at 17:12
  • not quite, I was confused not about the difference between passing a pointer and passing as a reference, but rather how you then use the 'reference variable' so to speak. – Dollarslice Oct 06 '11 at 17:15

2 Answers2

1

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

void foo(int& bar)
{
    bar = 5;
}

int foobar = 2;
foo(foobar);

you are invoking foo to be evaluated with the variable foobar, so essentially bar within foo becames foobar. The usual compiler impementation for this is to actually implement this code like this:

void foo(int* bar)
{
    *bar = 5;
}

int foobar = 2;
foo(&foobar);
K-ballo
  • 80,396
  • 20
  • 159
  • 169
0

If you did this:

void foo(int& bar) { bar = 6; }

int main() {
    int x = 3;
    foo(x);
}

x in main would equal 6. This is because a reference/alias (a different name for the same variable) is passed into foo. So, bar in function foo is the same variable as x in main, same memory location, and everything.

This is different from normal passing like this:

void foo(int bar) { bar = 6; }

int main() {
    int x = 3;
    foo(x);
}

where bar would be a new copy constructed value copied from x in main (note that copy constructor would better apply to a non-scalar type, but the idea is the same).

And lastly, if you did:

void foo(int* bar) { *bar = 6; }

int main() {
    int x = 3;
    foo(&x);
}

It would say "I want a pointer to an integer" for foo's parameter. In main, we take the "Address of stack variable x" which is in essence the same thing as a pointer to x, and we pass it into bar. Then dereferencing bar and assigning 6 to it would make x in main equal to 6 too :)

John Humphreys
  • 37,047
  • 37
  • 155
  • 255