Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

oop

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.

like image 887
Wagdi Kala Avatar asked Aug 16 '13 18:08

Wagdi Kala


People also ask

Can you change a const reference?

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

Is const reference type?

Technically speaking, there are no const references. A reference is not an object, so we cannot make a reference itself const. Indeed, because there is no way to make a reference refer to a different object, in some sense all references are const.

Does const reference make a copy?

Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .

Can reference variable be const?

A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it's a reference to const. Once a reference is bound to refer to an object, it can not be bound to refer to another object.


1 Answers

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.

like image 172
jrok Avatar answered Oct 05 '22 13:10

jrok