Ajeet Ganga
Ajeet Ganga

Reputation: 8653

Why does the constness of a reference affect whether it can be initialized with a variable of a different type?

Why does this code fail to compile?

 double d ;
 int & i1 = d // Compilation FAILS  

While this one does?

 double d ;
 const int & i = d // Compilation Succeeds

Please, I am interested in knowing what was in mind of C++ designers that they allowed one behavior while disallowed another.

I know in either case it's immoral, independent of technically possible or not. Also FYI I am using GCC on mac with "-O0 -g3 -Wall -c -fmessage-length=0"

Upvotes: 2

Views: 153

Answers (2)

Puppy
Puppy

Reputation: 146968

Because it creates a temporary int where the double is converted, and mutable references cannot bind to temporaries, whereas const ones can.

The problem with allowing mutable references to bind to temporaries is relatively clear.

Derived* ptr;
Base*& baseptr = ptr;
baseptr = new Base;
ptr->SomeDerivedFunction();

Upvotes: 2

James Curran
James Curran

Reputation: 103535

When you say

double d = 5.0; 
double &dd = d;

then dd changes as d changes. But, if you were to say,

const double &dd = d;

dd is a const double reference – its value cannot change, even if d changes, making the “reference” part of its definition impossible. Hence when you use const, the & causes a temporary to be created, and sets the reference to refer to that temporary. const int & i = d; therefore is effectively the same as const int i = d; which is allowed.

Upvotes: -1

Related Questions