How can I change the variable to which a C++ reference refers?

This is not possible, and that's by design. References cannot be rebound.


You can't reassign a reference, but if you're looking for something that would provide similar abilities to this you can do a pointer instead.

int a = 2;
int b = 4;
int* ptr = &a;  //ptr points to memory location of a.
ptr = &b;       //ptr points to memory location of b now.

You can get or set the value within pointer with: 

*ptr = 5;     //set
int c = *ptr; //get

With C++11 there is the new(ish) std::reference_wrapper.

#include <functional>

int main() {
  int a = 2;
  int b = 4;
  auto ref = std::ref(a);
  //std::reference_wrapper<int> ref = std::ref(a); <- Or with the type specified
  ref = std::ref(b);
}

This is also useful for storing references in containers.