let's say I have
class A {
double a;
double Value() const {
return a;
}
double& Value() {
return a;
}
}
//later:
A foo;
double b = foo.Value();
now, the non-const version will be called. Is there a nice way to force the use of the const version? I think it's possible with a cast but I don't think it's very elegant.
You may cast it to const
.
double b = static_cast<const A&>(foo).Value();
(I don't think I've ever explicitly added const
to a variable. I'm not sure if static_cast
is more appropriate than const_cast
.)
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