C++ mutable Keyword
The mutable
keyword in C++ is used to allow a member variable of a class to be modified, even if the object of the class is declared as const
. This provides an exception to the general rule that member variables of a const
object cannot be changed.
It is commonly used in scenarios where certain variables need to maintain state changes (e.g., caching or logging) without affecting the overall const-ness of the object.
Syntax
</>
Copy
class ClassName {
mutable data_type variable_name;
};
- mutable
- The keyword used to declare a mutable member variable.
- data_type
- The type of the variable, such as
int
,float
, etc. - variable_name
- The name of the member variable.
Examples
Example 1: Using mutable
in a const
Object
In this example, you will learn how the mutable
keyword allows modifying a member variable in a const
object.
</>
Copy
#include <iostream>
using namespace std;
class Counter {
private:
mutable int count; // Mutable variable
public:
Counter() : count(0) {}
void increment() const {
count++; // Allowed because 'count' is mutable
}
void display() const {
cout << "Count: " << count << endl;
}
};
int main() {
const Counter c;
c.increment(); // Modify mutable variable
c.increment();
c.display(); // Output the value of count
return 0;
}
Output:
Count: 2
Explanation:
- The class
Counter
has a mutable member variablecount
. - The
increment
method isconst
, meaning it cannot modify non-mutable members. - However, the mutable variable
count
is incremented inside theincrement
method, demonstrating the exception provided bymutable
.
Example 2: Using mutable
for Caching
In this example, you will learn how to use a mutable
variable to cache a computation result.
</>
Copy
#include <iostream>
using namespace std;
class Computation {
private:
mutable int cachedResult; // Cache for result
mutable bool isCached;
public:
Computation() : cachedResult(0), isCached(false) {}
int compute(int x) const {
if (!isCached) {
cachedResult = x * x; // Compute and cache the result
isCached = true;
}
return cachedResult;
}
};
int main() {
const Computation comp;
cout << "Result: " << comp.compute(5) << endl;
cout << "Cached Result: " << comp.compute(5) << endl;
return 0;
}
Output:
Result: 25
Cached Result: 25
Explanation:
- The class
Computation
uses a mutable variablecachedResult
to store the result of a computation. - The variable
isCached
, also mutable, tracks whether the computation has already been performed. - The
compute
method uses the cached result if available, avoiding redundant computations.
Key Points about mutable
Keyword
- The
mutable
keyword allows specific member variables of a class to be modified, even inconst
objects. - It is useful for scenarios like caching, logging, or maintaining internal counters.
- Only non-static member variables can be declared as
mutable
. - The
mutable
keyword does not affect the const-ness of other members or the class as a whole.