mutable Keyword
mutable allows a data member to be modified even inside a const member function.
This sounds strange, so the key idea is:
mutable is for data that does not change the logical meaning of the object.
Logical Constness
A const member function should not change the logical state of the object.
But it may need to update internal helper data such as:
- Cache value.
- Access count.
- Debug counter.
That is where mutable can be used.
Complete Example
#include <iostream>
#include <string>
using namespace std;
class Document {
private:
string title;
mutable int viewCount = 0;
public:
explicit Document(string documentTitle) : title(documentTitle) {}
void showTitle() const {
++viewCount;
cout << title << endl;
}
int getViewCount() const {
return viewCount;
}
};
int main() {
const Document doc("OOP Notes");
doc.showTitle();
doc.showTitle();
cout << "Views: " << doc.getViewCount() << endl;
return 0;
}
Output:
OOP Notes
OOP Notes
Views: 2
Why This Is Allowed
showTitle() is const, so it cannot change normal data members.
But viewCount is marked mutable, so it can change.
The document title does not change. Only an internal counter changes.
Use Carefully
Do not use mutable to cheat const-correctness.
Bad idea:
mutable double balance;
Changing a bank balance changes the logical state of the object, so it should not be mutable.
Viva Answer
The mutable keyword allows a data member to be modified inside const member functions. It should be used only for internal helper data that does not change the logical state of the object, such as cache or access counters.
Quick Check
- Can a mutable member change inside a const function?
- Should important state like
balancebe mutable? - What does logical constness mean?