C++ mutable Keyword
Example
Change a mutable attribute inside a const method:
class Car {
public:
string brand;
mutable int counter;
Car(string x) {
brand = x;
counter = 0;
}
void printBrand() const {
counter++; // OK, because counter is mutable
cout << brand << "\n";
}
};
int main() {
const Car myCar("Volvo");
myCar.printBrand();
myCar.printBrand();
cout << myCar.counter;
return 0;
}
Definition and Usage
The mutable keyword allows an attribute to be changed, even when the object is const, or inside a const method.
Normally, a const method cannot change any attributes. Use mutable for an attribute that is not really part of the object's data, like a counter that counts how many times a method is called.
Related Pages
Read more about classes in our C++ Classes and Objects Tutorial, and about const in our C++ Constants Tutorial.