Thursday, August 03, 2006

Constant Function

When should use constant function?
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
A () {i=5;}
void noChangeClassMember() const
i = 6; // error here, function should not modify i;
printf("%d\n", i);
void changeClassMember() { i =10;}
int i;

So how to modify the member variables in a const function?
use keyword 'mutable'
mutable int i;

1 comment: