Programming Tips - C++: make a change in a `const` member

Date: 2023oct25 Language: C++ Q. C++: make a change in a `const` member A. Lets say you have a member function that is mostly constant but has some side-effect like counting how many times its used. You don't want to unconst it. Make the use counter `mutable' like this:
#include <iostream> class Demo { int mThing = 0; public: // MUTABLE USE COUNTER (does not have to be public) mutable int mGets = 0; void setThing(const int n) { mThing = n; } // getThing() is const even thought its incrementing a counter int getThing() const { mGets++; return mThing; } }; int main() { Demo demo; demo.setThing(8); demo.getThing(); demo.getThing(); std::cout << "Gets: " << demo.mGets << "\n"; }
You could also cast `this` to non-const but the above is nicer. Just for completeness, here's the code for that cast way...
#include <iostream> class Demo { int mThing = 0; public: // NOT using `mutable` - only to show how int mGets = 0; void setThing(const int n) { mThing = n; } // getThing() is const even thought its incrementing a counter int getThing() const { Demo *pMe = (Demo *) this; pMe->mGets++; // pMe is non-const of this so can increment return mThing; } }; int main() { Demo demo; demo.setThing(8); demo.getThing(); demo.getThing(); std::cout << "Gets: " << demo.mGets << "\n"; }