Daemon
Daemon

Reputation: 1675

Reference to a reference in c++

I am going through Reference concepts in c++ and I am little confused by this statement in C++ Complete Reference.

You cannot reference another reference

So what is happening in this case:

    int  var = 10;
    int& ref = var;
    int& r_ref = ref;
    r_ref++;
    cout << "var:" << var << "ref:" << ref << "r_ref:" << r_ref << endl;

The output i am getting is:

var:11  ref:11  r_ref:11

Upvotes: 10

Views: 5010

Answers (3)

Andy Prowl
Andy Prowl

Reputation: 126412

So what is happening in this case:

What is happening is that you are creating another reference r_ref to the object referenced by ref, which is var. So you end up with two references to var: ref and r_ref.

Keep in mind that a reference is just an alias: after it is bound to an object (and it must be bound to some object at initialization time, and it cannot be re-bound later on), everything you do on the reference is done on the object being referenced, as if the reference was just an alternative name.

What this statement means:

You cannot reference another reference

Is that you cannot treat a reference itself as an entity that can be further aliased: references are aliases for objects, and whatever you do on a reference (including reference bounding!) is done on the object being referenced.

Upvotes: 8

LihO
LihO

Reputation: 42083

int var = 10; declares a variable var. Now when you write int& ref = var; defines a reference to var. You can look at ref as just an alias for var. Wherever you use ref it's like you would be using var directly.

So that's the reason why int& r_ref = ref; just defines another reference to var.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

It's slightly confusingly worded. What they mean is that you can't have a int& & type (note that there is such thing as a int&&, but that's a different type of reference).

In your code, the reference ref is referring to the object denoted by var. The names ref and var can be used interchangeably to refer to the same object. So when you do int& r_ref = ref;, you're not making a reference to a reference, but you're making a reference to that same object once again.

Upvotes: 17

Related Questions