wayfare
wayfare

Reputation: 1850

Changing References in C++

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

Upvotes: 0

Views: 162

Answers (5)

Dmitriy Kachko
Dmitriy Kachko

Reputation: 2914

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.

Upvotes: 0

bhuwansahni
bhuwansahni

Reputation: 1844

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..

Upvotes: 0

timestee
timestee

Reputation: 1096

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.

Upvotes: 0

Sid
Sid

Reputation: 7631

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?

Upvotes: 1

Xeo
Xeo

Reputation: 131799

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.

Upvotes: 2

Related Questions