I came across a code snippet
const int& reference_to_const_int = 20;
cout<<"
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
See Question&Answers more detail:os