Reputation: 10871
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?
Upvotes: 0
Views: 1046
Reputation: 109269
When you write
int i = 42;
double const &r = i;
i
is 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, so r
needs to be a double const&
for the above to work.
Upvotes: 4
Reputation: 96301
In C++ you can almost think of references as alias to another variable. They must match in non-cv qualified type, and in this case the types are different.
The reason it works with const double&
is becaused the compiler creates a temporary double
with a copy of i
's value and binds the const reference to that temporary. This is allowed because binding to a temporary extends the life of the temporary to the lifetime of the reference.
Upvotes: 4
Reputation: 361712
int i = 42;
double &r = i;
Here r
is a reference to double
, but i
is not a double
, then how can r
refer to it? It cannot. So it creates a temporary object of type double
out of the expression i
. But again, r
which is non-const reference, cannot bind to a temporary object.
However, if you make it const reference, then it would work:
double const & r = i;
Note that const
reference can bind to a temporary object which is created out of i
.
Upvotes: 6