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.
rnum1 = num2;
is not rebinding the reference.
It is setting rnum1
(and therefore num1
) to the value of num2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With