0

Here is my simple code

#include <iostream>
#include <string>

using namespace std;

int main() {
    
    string food = "Pizza";
    string &meal = food;
    
    string okay = "okay";
    
    &meal = okay; // showing error in updating meal reference
    
    cout << food << "\n";  // Outputs should be Pizza
    cout << meal << "\n";  // Outputs Should be okay
    return 0;
}

I reference have a meal variable to the same location as food so now the meal value is Pizza but now I want to update the meal reference location to okay such that the food value is still Pizza but the meal updated to okay.

is there any way to update the reference variable to another variable?

enter image description here

  • No, there's no way. Just use a pointer instead of a reference. – HolyBlackCat Dec 30 '22 at 07:15
  • A reference can't be rebind . Change `&meal = okay` to `meal = okay` See [why doesn't C++ allow rebinding a reference?](https://stackoverflow.com/questions/27037744/why-doesnt-c-allow-rebinding-a-reference) – Jason Dec 30 '22 at 07:16
  • @JasonLiam meal = okay also update food to okay I don't want that. – Alex Advent Dec 30 '22 at 07:25
  • 1
    A "reference" in C++ is nothing like a "reference" in Python or Java. All they have in common is the name. – molbdnilo Dec 30 '22 at 08:15

0 Answers0