Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I able to rebind a reference after its initialization? [duplicate]

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.

like image 282
John Avatar asked Sep 12 '25 07:09

John


1 Answers

rnum1 = num2; is not rebinding the reference.

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

like image 86
Bathsheba Avatar answered Sep 14 '25 22:09

Bathsheba