I have couple of questions related to usage of references in C++.
In the code shown below, how does it work and not give a error at line
q = "world";
?#include <iostream> using namespace std; int main() { char *p = "Hello"; char* &q = p; cout <<p <<' '<<q <<"\n"; q = "World"; //Why is there no error on this line cout <<p <<' '<<q <<"\n"; }
How can a reference q be reinitialized to something else?
Isn't the string literal,
p = "Hello"
, a constant or in read-only space? So if we do,q = "World";
wouldn't the string at
p
which is supposed to be constant be changed?
I have read about C++ reference type variables as they cannot be reinitialized or reassigned, since they are stored 'internally' as constant pointers. So a compiler would give a error.
But how actually a reference variable can be reassigned?
int i; int &j = i; int k; j = k; //This should be fine, but how we reassign to something else to make compiler flag an error?
I am trying to get hold of this reference, and in that maybe missed some key things related, so these questions.
So any pointers to clear this up, would be useful.