What it does is effectively make the this
pointer be a const pointer to const instead of a const pointer to non-const. So, any time that you reference this
in a const member function - either explicitly or implicitly - you're using a const pointer to const.
So, in the case of the class you have here, in any non-const function, the type of this
is WithStatic const *
while in the const functions, its type is const WithStatic * const
.
Like with any pointer to const, you can't alter anything that it points to. So, you can't alter any of its member variables, and you can't call any of its non-const member functions.
Generally speaking, it's a good idea to make a member function be const if you can reasonably do so, because it guarantees that you're not going to alter the object's state, and you can call it with a const object.
It is possible for member variables to be altered if they're mutable
or volatile
, but those are more advanced topics that are probably better avoided until you're more familiar with the language. Certainly, you don't usually need to worry about them and shouldn't use them unless you need to. It's also possible to cast away the constness of the this
pointer, at which point you could alter it, but IIRC, that's undefined behavior, and it's definitely generally considered a bad idea. So, there are instances where it's possible to alter an object's state within a const member function, but it's not normally possible and best avoided even when it is.
When you make a member function const, you're effectively promising that the object's state will not be changed by that function call (though there can obviously be side effects as evidenced by the fact that you can call functions like printf()
).