References and Pointer in C++

It is written alias cannot be changed to alias something else but it is working:

on this page

https://www.codecademy.com/courses/learn-c-plus-plus/lessons/cpp-references-and-pointers/exercises/references

You are not changing the alias to alias something else, you are creating an alias for an alias:

int main() {
  int soda = 99;    //soda = 99
  
  int &pop=soda;    //pop = soda = 99

  int &else1 = pop; //else1 = pop = soda = 99
}

Changing an alias to alias something else won’t work:

int main() {
  
  number = 99;
  number2 = 55;

  int &n = number; //n = number
  int &n = number2;
  //   \ 
  //    attempting to assign n as an alias to number2 throws an error
}

main.cpp: In function ‘int main()’:
main.cpp:19:8: error: redeclaration of ‘int& n’
   int &n = soda;
        ^
2 Likes

Thanks I understood :grinning:

1 Like