Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference with constant modifier

FirstOne::

double & val = 66.6;     //illegal
const double & val = 66.6;   //legal

I was just doing some demo programs and came through the above concept but not able to identify what exactly the need of the above concept . what magic exactly const is doing in the second case ?

SecondOne::

int nVar = 12;
int &rVar = nVar ;//Ok
double &dVar = nVar ;//Error
const double &cdVar = nVar ;//Ok

Why the 3rd statement is not working where as 4th statement is working ?

like image 224
Viku Avatar asked Dec 03 '25 11:12

Viku


2 Answers

The first is illegal. You cannot bind a non-const reference to a temporary.

The second is legal. It creates a temporary double, initialized to 66.6, and makes val a const reference to it.

The const promises not to change the value through the reference. C++ does not permit you to bind a non-const reference to a temporary because that's usually an error.

like image 193
David Schwartz Avatar answered Dec 06 '25 00:12

David Schwartz


Let me show you.

void f(Base*& p) { p = new Base; }
int main() {
    Derived* d;
    f(d); // Creates temporary Base* and calls f with it
    // Dude, where's my object?
}

As you can see, this introduces a nasty error. Firstly, the object is leaked and cannot be recovered, as the argument to f does not actually refer to d at all. Secondly, even if d were successfully mutated in f, it would be of the wrong type and violate the type system.

like image 31
Puppy Avatar answered Dec 05 '25 23:12

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!