Here is some code copied from Thinking in C++ Vol1 Chapter 10.
#include <iostream>
using namespace std;
int x = 100;
class WithStatic {
static int x;
static int y;
public:
void print() const {
cout << "WithStatic::x = " << x << endl;
cout << "WithStatic::y = " << y << endl;
}
};
what’s the meaning of const for the function print()? Thanks!
I’ve heard this described previously as “a method that does not logically change the object”. It means that by calling this method the caller can expect the object’s state to remain the same after the method returns. Effectively, the
thispointer becomes a constant pointer to a constant instance of that class, so member variables cannot be altered. The exception to this rule is if member variables are declared withmutable. If a class hasmutablemember variables, these can be modified by both non-const and const methods. Also, non-const methods cannot be called from within a const method.Some people use
mutablemember variables to cache results of timely computations. In theory, the state of the object does not change (i.e. the only effect is that subsequent calls are quicker, but they produce the same results given the same input).