I came across a code snippet
const int& reference_to_const_int = 20;
cout<<"\n reference_to_const_int = "<<reference_to_const_int<<endl;
This code compiles & executes with output :-
reference_to_const_int = 20
This is something strange in for me. As I know reference do not occupy memory & they are aliases to other variables. hence we cannot say
int& reference_to_int = 30;
The above statement shall not compile giving error :-
error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
What exactly is happening in the “const int&” case? A full explanation is desired.
Kindly help.
Thanks
A temporary is created, and it’s legal to bind a
constreference to it, but illegal to bind it to a non-constone.It’s just like:
A
constreference extends the life of a temporary, that’s why this works. It’s just a rule of the language.