In the following example I found on the net, it is mentioned that one of the advantages of const_cast
is that it allow a constant function changes the class members. It is a question to me. Why should we set a rule for a function by const
and then breaking that rule with const_cast
? Isn't it like a cheating? Wouldnt it better to not set const
for the function at all?
#include <iostream>
using namespace std;
class student
{
private:
int roll;
public:
student(int r):roll(r) {}
// A const function that changes roll with the help of const_cast
void fun() const
{
( const_cast <student*> (this) )->roll = 5;
}
int getRoll() { return roll; }
};
int main(void)
{
student s(3);
cout << "Old roll number: " << s.getRoll() << endl;
s.fun();
cout << "New roll number: " << s.getRoll() << endl;
return 0;
}
reference
That is indeed a bad idea. As well as lying about the function's behaviour, it allows you to modify a member of a constant student
object, giving undefined behaviour.
In general, a member function should be const
if, and only if, it doesn't modify the object's observable state. So in this case, it should not be const
.
Sometimes, you might want specific members to be modifiable in a function that doesn't otherwise cause an observable change; for example, locking a mutex to access shared data, or caching the result of a complex calculation. In that case, declare those members mutable
, so that the rest of the class is still protected by const
-correctness.
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