They are both correct.
The const member function cannot change the state of an object .
- This means that it can read (but not change) all member variables.
- It also means that it can only call other constant member functions.
Other methods that guarantee not to change the state of an object.
Variable members are also mentioned over James.
Therefore, I must also highlight them here.
A modified member variable is a variable that is not part of the state of the object (the compiler does not consider it part of the state of objects). You should also relate to it this way. Any member variable that contains information about the state of an object should NOT be marked as mutable. You should only use it to store temporary information that can be rebuilt from the state of objects.
A simple example is an object with a date. Where the object has a method that converts data / time into a readable string format. This line can be cached in an object in a mutable member for efficiency (so you don't have to create the line multiple times). But the string is not part of the state of the object (because it can be built from other members).
In addition, James mentions above, crowding out the constellation using const_cast .
Except in special situations where you know an object CANNOT be const, this is considered a universal bad idea. Because this leads directly to undefined behavior. If you need to drop the constant, then something very wrong will happen in your program in your program.
In fact, I can only think of one situation when this happens normally. And then I do not want to comment on it before I go and do research to make sure that I do not look stupid.
Martin york
source share