0
#include <iostream> using namespace std; int main() { int i=9,k=8; int &q=i; q=k; cout<<i<<"\n"<<q<<"\n"; return 0; } 

Output:

8 8 

But in my book it is given "q=k changes only the value of i and not q. This is because q being a reference gets de-referenced automatically as(*q). Hence the value at the address stored in q is replaced by value of i" But as you can see value of q also gets changed. Isn't it wrong???

1
  • References cannot be reseated. Commented Dec 24, 2013 at 7:14

4 Answers 4

2

q, as a reference, does not change. In other words, it refers to i, always, forever and ever (until it goes out of scope). You cannot make q refer to a different object. That is what is meant by "it's value [sic?] never changes." The "value" of q is i's address. When you assign to q there, you're really assigning to i.

What you printed out there was the value of i, and then the value of the object that q refers to (which is i).

Sign up to request clarification or add additional context in comments.

Comments

0

As q is reference to i, that means it is just an alias to i (other name to i).

So whatever value i will have same q will have!

Comments

0

When you initialize a reference as follow

int i = 9; int &q =i; 

q just becom another alias (you can say nickname) of i, so if any change occurs in q it will reflect in i as well and vice-versa.

Comments

0

When you initialize a variable like:

int &q = i;

every time you change i you change q and viceversa.

The reference of q have the same value of i, so them point to the same memory location.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.