Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IS reference to a reference illegal in C++?

Tags:

c++

reference

int main(){
int ival=1024;
int &refVal=ival;
int &refVal2=refVal;
return 0;
}

C++ Primer(5th edition) says "Because references are not objects, we may not define a reference to a reference."(Chinese 5th version says "不能定义引用的引用".meaning can't define a reference to a reference. )

But I got the code above pass compilation.

What's going on?

Feel free to correct any errors(including my English skills)

like image 232
guangzhi Avatar asked Feb 06 '15 06:02

guangzhi


People also ask

Is reference to a reference allowed?

A reference is an alias to the object itself. So when you try to make a reference to a reference, the reference passes it on to the object itself so you end up with just another reference to the object.

Is reference to a reference allowed in C++?

C++ references differ from pointers in several essential ways: It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references. Once a reference is created, it cannot be later made to reference another object; it cannot be reseated.

Can we reassign reference?

Remember, once you initialize a reference, you cannot reassign it. A reference practically stands for an object. You cannot make it 'point' to a different object.

Does C have reference operator?

Easy To Learn Reference operator (&) In C Language. This referencing operator is also called address operator, which gives the address of a variable, in which location the variable is resided in the memory.


2 Answers

After refVal is initialized, whenever you mention its name, it behaves like the variable ival it refers to---its "referenceness" can no longer be detected (except by decltype). Therefore refVal2 is simply initialized to refer to ival also.

There is no type "reference to reference to int", int&(&).

like image 172
Brian Bi Avatar answered Sep 19 '22 17:09

Brian Bi


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

Perhaps they meant to say:

int i = 10;
int& ref1 = i;
int&& ref2 = ref1; // Not allowed.

Of course, in C++11, the symbol && is used to define rvalue references.

I think it's more illustrative to compare references and pointers to understand why references to references does not make sense.

enter image description here

like image 37
R Sahu Avatar answered Sep 19 '22 17:09

R Sahu