c++referenceimplicit-conversionexplicit-conversion

Why non const reference cannot be initialized to an object of different type?


I was reading this book and it is written that We can assign const reference of one type to an object of any other type, and the reason was given that, internally compiler assign the Rvalue to the object of the same type as reference and then const reference is initialized to that object of same type, But, if this type of implicit conversion is helping in getting const reference assigned to different type of objects, then why it is not possible to do that same conversion implicitly, because for this explicit conversion.

#include<iostream>
using namespace std;
int main()
{
    int a = 10;

    double temp = (double)a;
    double &x = temp;
    cout << x << endl;
    return 0;
}

It is working the same way, why it is not pre-configured in the compiler?


Solution

  • If the compiler has to perform an implicit conversion from one type to another, that means it has to create a temporary to hold the converted value.

    A non-const reference cannot bind to a temporary. Period.

    A const reference can, and it will extend the lifetime of the temporary.

    In other words:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        int a = 10;
    
        double &x = (double)a; // ERROR! Can't bind to the temporary double
        cout << x << endl;
    
        const double &x2 = (double)a; // OK! Binds to the temporary double
        cout << x2 << endl;
    
        return 0;
    }
    

    Live Demo