const tells the compiler that a variable is immutable (cannot be changed after initialization). It is used to declare constant variables and also for methods that guarantee not to change the state of the object.
mutable allows changing the value of a class member even inside const methods.
volatile informs the compiler that the value of a variable may be changed outside the program's control (e.g., by hardware), and the compiler should not optimize access to it.
class Logger { public: void log() const { ++count; // Allowed — count is declared mutable } private: mutable int count = 0; }; volatile int flag; void wait() { while (flag == 0) { /* the compiler does not optimize the loop as flag is volatile */ } }
"What happens if a class member is declared as both
constandmutable?"
Answer: This cannot be done, as they are mutually exclusive qualifiers; the compiler will issue an error.
Story
In industrial software for working with hardware, a developer declared data updated by external interrupts as ordinary int. Compiler optimization removed repeated reads of these variables, causing the program to "hang" in an infinite loop. The problem was diagnosed only after replacing it with
volatile int.
Story
One of the logging classes had a method
log() const, where it was necessary to update the call counter. Initially, this was done using aconst_castpointer, which caused many warnings and non-obvious bugs. The problem disappeared after correctly declaring the counter usingmutable.
Story
_Some methods of the class were declared as
const, but pointer-type members were modified (for example, to implement caching). This led to violations of "const-correctness" logic and even UB, if the object was actually located in a read-only area.mutableshould be used or the design should be changed.