fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class IntRef {
  5. int *ptr;
  6. int copy;
  7. public:
  8. IntRef(int& d) : ptr(&d) {}
  9. IntRef& operator=(const int& rhs) {
  10. // Detach from the original on assignment
  11. copy = rhs;
  12. ptr = &copy;
  13. }
  14. operator int() const {
  15. return *ptr;
  16. }
  17. };
  18.  
  19. int main() {
  20. int x = 5; //Original variable
  21. IntRef y(x); //Reference variable to x.
  22. x = 5; //Modifying original variable.
  23. cout<<x<<" "<<y<<endl;
  24. y = 10; //Modifying reference variable.
  25. cout<<x<<" "<<y<<endl;
  26. return 0;
  27. }
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
5 5
5 10