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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With