Printing variable value using Reference to const gives different result
I am learning about references in C++. So i am trying out different examples to better understand the concept. One example that i could not understand is given below:
double val = 4.55;
const int &ref = val;
std::cout << ref <<std::endl; //prints 4 instead of 4.55
I want to know what is the problem and how can i solve it?
Solution 1:
The problem is that the reference ref
is bound to a temporary object of type int
that has the value 4
. This is explained in more detail below.
When you wrote:
const int &ref = val;
a temporary of type int
with value 4
is created and then the reference ref
is bound to this temporary int
object instead of binding to the variable val
directly. This happens because the type of the variable val
on the right hand side is double
while on the left hand side you have a reference to int
. But for binding a reference to a variable the types should match.
For solving the problem you should write:
const double &ref = val; //note int changed to double on the left hand side
The above statement means ref
is a reference to const double
. This means we cannot change the variable val
using ref
.
If you want to be able to change val
using ref
then you could simply write:
double &ref = val;