Are parameters by reference automatically "dereferenced"?

I had never thought of this before, but I noticed that the & operator behaves differently when used as an "address of" operator and as a reference parameter.
Example:

This code will print a memory address because *b holds a memory address (the one where the variable a lives):
1
2
3
4
5
6
7
int main()
{
  int a=5;
  int* b=&a;

  cout << b << endl;
}


But in this case the function won't print a memory address but the actual value stored in that address:

1
2
3
4
5
6
7
8
void function(int &b){
    cout << b << endl;
}
int main()
{
  int a=5;
  function(a);
}


So why is it that way? Does the & operator mean that whenever I use that parameter within the function it will automatically dereference it, instead of treating it as a memory address? Does this also mean that there is no way to print the memory address stored in parameter b (which is variable a's memory address) within the function?
The problem is that & is overloaded to mean different things, depending on context.

In your first example (line 4) it is the “get the address of” operator, returning a pointer to the rhs argument.

In your second example (line 1) it is not an operator at all, but part of the argument type — the argument is a reference to int (or int reference).

The best way to think of a reference is as an alias for another thing. So, given:

1
2
int  x = 7;
int& y = x;

You now have two names for a single integer object. You can use either name to access the (singular) integer object.


This way of thinking is a bit unique, especially for those coming from the value-vs-pointer thinking from before. When using (C++) references, don’t treat them like pointers. They are not.

The underlying implementation may actually use pointers, if necessary, but that does not (and should not) matter to you.

Hope this helps.

[edit]
I think you might benefit from reading something I was considering for the FAQ from ages ago (that I have not had time to mess with for years). I am not entirely happy with the current presentation, but you can read the two pages anyway. I hope they are of value to you.

https://michael-thomas-greer.com/faq/values-pointers-references/ (part 1)
https://michael-thomas-greer.com/faq/pass-by/ (part 2)

C++ is a weird language.
Good thinking!
Last edited on
To understand the funny syntax, you have to realize that C++ was built on top of C. The first implementations actually pre-processed C++ code into C code and then compiled the result.

So the C++ syntax was designed to avoid conflicting with C. I suspect that the use of & for reference is a result of that.
I suspect that they just ran out of symbols to use. Everything you can touch on the keyboard has meaning in C...
Topic archived. No new replies allowed.