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.


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.