Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do parameters passed by reference in C++ not require a dereference operator?

I'm new to the C++ community, and just have a quick question about how C++ passes variables by reference to functions.

When you want to pass a variable by reference in C++, you add an & to whatever argument you want to pass by reference. How come when you assign a value to a variable that is being passed by reference why do you say variable = value; instead of saying *variable = value?

void add_five_to_variable(int &value) {
    // If passing by reference uses pointers,
    // then why wouldn't you say *value += 5?
    // Or does C++ do some behind the scene stuff here?
    value += 5; 
} 

int main() {

  int i = 1;
  add_five_to_variable(i);
  cout << i << endl; // i = 6

  return 0;
}

If C++ is using pointers to do this with behind the scenes magic, why aren't dereferences needed like with pointers? Any insight would be much appreciated.

like image 262
ab217 Avatar asked Sep 22 '11 06:09

ab217


1 Answers

When you write,

int *p = ...;
*p = 3;

That is syntax for assigning 3 to the object referred to by the pointer p. When you write,

int &r = ...;
r = 3;

That is syntax for assigning 3 to the object referred to by the reference r. The syntax and the implementation are different. References are implemented using pointers (except when they're optimized out), but the syntax is different.

So you could say that the dereferencing happens automatically, when needed.

like image 50
Dietrich Epp Avatar answered Oct 23 '22 07:10

Dietrich Epp