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.
This is not possible, and that's by design. References cannot be rebound. You are not changing the reference, you are assigning the value of k to the object referred to by x .
However, in Python, variable is just a name given to an object in the memory. Even if we assign its value to another variable, both are in fact referring to same object in memory. This can be verified by id() function. It therefore is clear that in Python, we can not create reference to a variable.
To assign reference to a variable, use the ref keyword. A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. Declare the reference parameters using the ref keyword.
An array of references is acceptable. We can also create a reference to a reference.
q
, it changes p
.p
is a pointer which points at a literal. The pointer can be changed, what is being pointed to cannot. q = "world";
makes the pointer p
point to something else.You seem to think that this code
int i; int &j = i; int k; j = k;
is reassigning a reference, but it isn't. It's assigning the value of k
to i
, j
still refers to i
. I would guess that this is your major misunderstanding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With