Wagdi Kala
Wagdi Kala

Reputation: 53

Why once I've declared a reference as a const then it can take a different type of data?

Hello i'm trying to figure out this thing..

Say i have this code.

int a = 5;
double& b = a; //Error.

Then once I've declared the second line as a const the compiler doesn't complain anymore.

const double& b = a; //Correct.

what is really going on behind the scene, why const solves the problem.

Upvotes: 5

Views: 117

Answers (2)

jrok
jrok

Reputation: 55395

An int needs to be converted to double first. That conversion yields a prvalue temporary and these can't bind to references to non-const.

A reference to const will extend the lifetime of the temporary that would otherwise be destroyed at the end of the expression it was created in.

{
    int a = 0;
    float f = a; // a temporary float is created here, its value is copied to
                 // f and then it dies
    const double& d = a; // a temporary double is created here and is bound to 
                         // the const-ref
}   // and here it dies together with d

If you're wondering what a prvalue is, here's a nice SO thread about value categories.

Upvotes: 7

James Kanze
James Kanze

Reputation: 153909

What's happening behind the scenes is an implicit conversion of an int to a double. The result of an implicit conversion is not an lvalue, so it cannot be used to initialize a non-const reference.

Upvotes: 6

Related Questions