In the book I am reading, it says that the type of a reference must match the type of the object to which the reference refers. If that is true I would expect that the code below would not compile, but it compiles no problem.
if you remove the const from this code snippet, as shown below then compilation fails as expected. Does the rule that the types must match not apply to const references?
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int main()
{
double dval = 3.14;
int &ri = dval;
cout << ri << "\n";
return 0;
}
Reading a bit further reveals the following quote which seems to answer my question.
The first exception is that we can initialize a reference to const from any expression that can be converted to the type of the reference. In particular, we can bind a reference to const to a non const object, a literal, or a more general expression:
For the first version of the code ri is bound to a temporary object of type int. The lifetime of the temporary object is extended to the lifetime of the (local const) reference, so the reference does match the type of the object it refers to.