lundi 17 juillet 2017

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

This question already has an answer here:

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.

Aucun commentaire:

Enregistrer un commentaire