Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to a reference in c++

Tags:

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
like image 473
Daemon Avatar asked May 10 '13 11:05

Daemon


1 Answers

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.

like image 99
Joseph Mansfield Avatar answered Oct 14 '22 16:10

Joseph Mansfield