I am trying to understand the concept of assigning a float to const reference double and the value of double doesn't change if the float value updated.
float d = 2.0;
const double & f = d;
d = 3.0;
std::cout << d << " " << f << std::endl;
output:
3 2
What is the reason behind this.
However this issue is not seen when we set the reference variable as the same type as the other variable.
However this issue is not seen when we set the reference variable as the same type as the other variable
That's the point; you can't bind reference to object with different type directly.
Given const double & f = d;
, a temporary double
will be constructed from d
, then bound to the reference f
. The modification on d
has nothing to do with the temporary; they're two irrelevant objects. That's why you got different result when print out d
and f
.
BTW: Only the lvalue reference to const and rvalue reference could be bound to temporary, so const double & f = d;
and double && f = d;
work fine. Lvalue reference to non-const can't be bound to temporary, then double & f = d;
won't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With