0
0
CppConceptBeginner · 3 min read

What is mutable keyword in C++ and How It Works

In C++, the mutable keyword allows a member variable of a class to be modified even if the containing object is declared const. This means you can change that specific variable inside a const method, bypassing the usual immutability rules.
⚙️

How It Works

Imagine you have a notebook that you promised not to change. Normally, if you mark the notebook as "do not change," you can't write anything new in it. But what if you want to keep track of how many times you looked at the notebook without breaking your promise? The mutable keyword in C++ works like a special pencil that lets you write notes about your usage without changing the main content.

In programming terms, when an object is declared const, you cannot change its member variables inside its methods. However, if a member variable is marked as mutable, it can be changed even in these const methods. This is useful for things like caching or counting how many times a function is called, where the change does not affect the object's logical state.

💻

Example

This example shows a class with a mutable variable that counts how many times a const method is called. Even though the method promises not to change the object, it can update the counter.

cpp
#include <iostream>

class Example {
private:
    mutable int callCount = 0; // can be changed even in const methods
public:
    void show() const {
        callCount++; // allowed because callCount is mutable
        std::cout << "show() called " << callCount << " times\n";
    }
};

int main() {
    const Example ex;
    ex.show();
    ex.show();
    return 0;
}
Output
show() called 1 times show() called 2 times
🎯

When to Use

Use mutable when you need to modify some internal data of an object even if the object is logically constant. This is common for:

  • Keeping counters or statistics inside const methods.
  • Implementing lazy evaluation or caching results without changing the object's visible state.
  • Tracking debugging or logging information.

It helps keep the interface clean by allowing methods to be const while still updating internal bookkeeping details.

Key Points

  • mutable allows modification of specific members in const objects.
  • It is useful for internal state changes that don't affect the object's logical state.
  • Only applies to non-static member variables.
  • Use it carefully to avoid confusing code behavior.

Key Takeaways

The mutable keyword lets you change specific members even in const objects.
It is ideal for counters, caches, or debugging info inside const methods.
Mutable only works on non-static member variables.
Use mutable to keep const correctness while allowing internal updates.