I met two explanation of const member function
class A{
public:
...
void f() const {}
...
}
I think the second one is right. But why does the first one come out? Is there anything to be clarify?
Thanks!
You can examine all class member values in a const member function, and in some cases you can even change the value of member variables. The first explanation is incorrect, I don't know where it comes from. The second explanation is correct, but with a few exceptions.
There are some exceptions to this rule. You can also change mutable variables in a const member function, for example a member variable declared like this:
mutable float my_rank;
You can also break const-correctness in a class by const_cast'ing a reference to yourself like this:
Class* self = const_cast<Class*> (this);
While technically allowed in C++, this is usually considered poor form because it throws away all of the const modifiers of your design. Don't do this unless you actually have to, and if you find yourself having to do this quite a lot that suggests a problem with your design. The C++ FAQ covers this very well.
Here are two references in case you want to do more reading: