4

According to C++ Primer, by Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo:

Once initialized, a reference remains bound to its initial object. There is no way to rebind a reference to refer to a different object.

How, then, am I seemingly able to rebind the reference I initialized to another object in the following code?

#include <iostream>

int main()
{
     int num1 = 10;
     int num2 = 20;

     int &rnum1 = num1;

     std::cout << rnum1 << std::endl;   // output: 10

     rnum1 = num2;

     std::cout << rnum1 << std::endl;   // output: 20

     return 0;
}

From my understanding num1 and num2 are two different objects. The same type, yes, but two completely different objects.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
John
  • 79
  • 1
  • 9

2 Answers2

7

rnum1 = num2; is not rebinding the reference.

It is setting rnum1 (and therefore num1) to the value of num2.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
4

rnum1 is another name for num1

when you write rnum1 = ... it is if you were to write num1 = ..., because rnum1 is another name for num1.

So the reference itself is not rebound to another variable, what you have here is simple assignment of num1.

To really prove it , you can print the memory addresses of num1, num2 and rnum1:

#include <iostream>

int main()
{
     int num1 = 10;
     int num2 = 20;

     int &rnum1 = num1;

     std::cout << rnum1 << std::endl;   // output: 10

     rnum1 = num2;

     std::cout << rnum1 << std::endl;   // output: 20
     std::cout << &num1 << " " << &rnum1 <<" "<< &num2 << std::endl;
     return 0;
}
David Haim
  • 25,446
  • 3
  • 44
  • 78