Why is the mutable keyword needed in C++? Only for const methods?
Hi everyone! I'm learning C++ and came across the `mutable` keyword. Textbooks say it allows modifying a class member even in `const` methods. But this seems strange to me — why would you want to change anything in a method that is marked as const? Doesn't this violate the whole idea of constness?
Here's an example I wrote:
```cpp
class Counter {
private:
mutable int accessCount = 0;
int value = 0;
public:
int getValue() const {
accessCount++; // works because of mutable
return value;
}
int getAccessCount() const {
return accessCount;
}
};
```
I understand that `accessCount` is a counter for getter calls. But wouldn't it be better to just remove `const` from the `getValue()` method? Or use `const_cast`? It seems to me that `mu