What is a constant reference? (not a reference to a constant)
A pretty theoretical question...Why do constant references not behave the same way as constant pointers so that I can actually change the object they are pointing to? They really seem like another plain variable declaration. Why would I ever use them? This is a short example that I run which compiles and runs with no errors:
int main (){
int i=0;
int y=1;
int&const icr=i;
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99; // Can assign another value but the value is not assigned to y...
int x=9;
icr=x;
cout<<"icr: "<<icr<<", y:"<<y<<endl;
}
Solution 1:
The clearest answer. Does “X& const x” make any sense?
No, it is nonsense
To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.
In other words, “X& const x” is functionally equivalent to “X& x”. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said “const X& x”.
Solution 2:
The statement icr=y;
does not make the reference refer to y
; it assigns the value of y
to the variable that icr
refers to, i
.
References are inherently const
, that is you can't change what they refer to. There are 'const
references' which are really 'references to const
', that is you can't change the value of the object they refer to. They are declared const int&
or int const&
rather than int& const
though.
Solution 3:
What is a constant reference (not a reference to a constant)
A Constant Reference is actually a Reference to a Constant.
A constant reference/ Reference to a constant is denoted by:
int const &i = j; //or Alternatively
const int &i = j;
i = 1; //Compilation Error
It basically means, you cannot modify the value of type object to which the Reference Refers.
For Example:
Trying to modify value(assign 1
) of variable j
through const reference, i
will results in error:
assignment of read-only reference ‘i’
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99;
Doesn't change the reference, it assigns the value of the type to which the reference refers. References cannot be made to refer any other variable than the one they are bound to at Initialization.
First statement assigns the value y
to i
Second statement assigns the value 99
to i
Solution 4:
By "constant reference" I am guessing you really mean "reference to constant data". Pointers on the other hand, can be a constant pointer (the pointer itself is constant, not the data it points to), a pointer to constant data, or both.