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;
}