1

I was going through the C++ Primer book and I came across the following two statements:

  1. Because references are not objects, we may not define a reference to a reference.

  2. Because references are not objects, they don’t have addresses. Hence, we may not define a pointer to a reference.

However, when I run the following code, I don't get errors or warnings and my code runs fine:

int main(int argc, const char * argv[]) {
    // insert code here...

    int i, &ri = i;
    int &bi = ri;

    std::cout << "The address of ri is " << &ri << std::endl;
    std::cout << "The address of bi is " << &bi << std::endl;

    int* p = &ri;
    std::cout << p << std::endl;

    return 0;
}

Output:

The address of ri is 0x7fff5fbff76
The address of bi is 0x7fff5fbff76c
0x7fff5fbff76c

Any idea why this works?

Thanks.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • Because they are all references to the same variable. Good reading, and probable duplicate here: [Is there any way to find the address of a reference?](http://stackoverflow.com/questions/1950779/is-there-any-way-to-find-the-address-of-a-reference) – user4581301 Feb 09 '17 at 05:22
  • [`'\n'` should be used rather than `endl`](http://stackoverflow.com/q/213907/995714) – phuclv Feb 09 '17 at 05:34
  • Your first output is missing the trailing `c`, but that's definitely a typo. – Quentin Feb 09 '17 at 12:31

3 Answers3

0

What they mean is that you can't have a int& & type.

In your code, the reference ri is referring to the object i.

And when you do int &bi = ri; you're not making a reference to a reference, but you're making a reference to that same object once again.

Moshe D
  • 768
  • 1
  • 4
  • 13
0

In the above code, you have not created any kind of variable to hold the address of reference.

Logical meaning to hold address of reference in your code will be:

int &bi = &ri;

but this code gives error.

And hence your code is working, because you have created variables, all of which hold address of variable i.

Deepak Tatyaji Ahire
  • 4,883
  • 2
  • 13
  • 35
0

int &bi = ri;

this means "set the reference bi equal to the reference ri". In the same way as you assign any other simple type.

int* p = &ri;

the clever compiler substitutes the "address of reference" with the "address of the object the reference references to".

KonstantinL
  • 667
  • 1
  • 8
  • 20