Error!
$ cat double.cc
#include<iostream>
int main() {
int i = 42;
double &r = i;
}
$ g++ double.cc
double.cc: In function ‘int main()’:
double.cc:5: error: invalid initialization of reference of type ‘double&’
from expression of type ‘int’
$
Works!
$ cat double.cc
#include<iostream>
int main() {
int i = 42;
const double &r = i;
}
$ g++ double.cc
$
Why do we get the error in the first case? I know this is discussed here, but I am not sure I understand why this not allowed, while int to const double& is allowed?
When you write
iis implicitly converted to a double, which results in a temporary value, or rvalue. A non-const reference is not allowed to bind to an rvalue, sorneeds to be adouble const&for the above to work.