Constant function is a function in a class that does not change the class member. Defining a constant function can enforce that the function doesn't change any data member in the class unwantedly, and reduce significant errors. Here is how to define it:
class A
{
public:
A () {i=5;}
void noChangeClassMember() const
{
i = 6; // error here, function should not modify i;
printf("%d\n", i);
}
void changeClassMember() { i =10;}
private:
int i;
};
So how to modify the member variables in a const function?
use keyword 'mutable'
mutable int i;
No comments:
Post a Comment