0

From C++ FAQ

"How can you reseat a reference to make it refer to a different object?"

But when I do this it compiles and executes fine.

    int f = 5;
int y =4;
int& u = f;
u = y;
B& bRef = B();
bRef = B();

This code is inside my main() function.

Link of C++ FAQ https://isocpp.org/wiki/faq/references#reseating-refs

seaotternerd
  • 6,298
  • 2
  • 47
  • 58
wayfare
  • 1,802
  • 5
  • 20
  • 37

5 Answers5

2

You don't reseat the reference, you simply assign to the referred object.

#include <iostream>

struct X{
  void operator=(X const&){
    std::cout << "Woops, assignment!\n";
  }
};

int main(){
 X x, y;
 X& rx = x;
 rx = y;
}

Guess what this prints.

Xeo
  • 129,499
  • 52
  • 291
  • 397
1

By saying int &u=f; and then u=y; you are assigning the value of y to f as f is referred to by the reference u. Hence you are not reseating the reference but simply changing the value of f.

Why is it illegal/immoral to reseat a reference?

Community
  • 1
  • 1
Sid
  • 7,511
  • 2
  • 28
  • 41
0

You are not changing the reference while saying u = y;. You are just assigning value of y to variable f which still referred by u.

Please check the value of f to see the effect.

Dmitriy Kachko
  • 2,804
  • 1
  • 19
  • 21
0

when you call 'u = y;',you just assign value of y to the variable that u reference to(its f). Basically,reference is implemented as a 'pointer' under varies compiler, the operation 'u = y;', just set the memory to value of y.

timestee
  • 1,086
  • 12
  • 36
0

The value of a reference cannot be changed after it has been initialized; it always refers to the same object it was initialized to denote..

bhuwansahni
  • 1,834
  • 1
  • 14
  • 20