ProgrammingSystem/C++ Developer

Tell us about the differences between the keywords 'mutable', 'volatile', and 'const' in C++. What are they used for, what typical mistakes arise from their incorrect use?

Pass interviews with Hintsage AI assistant

Answer

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.

Code example

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 */ } }

Trick question

"What happens if a class member is declared as both const and mutable?"

Answer: This cannot be done, as they are mutually exclusive qualifiers; the compiler will issue an error.


Examples of real mistakes due to a lack of knowledge about the topic.


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 a const_cast pointer, which caused many warnings and non-obvious bugs. The problem disappeared after correctly declaring the counter using mutable.


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. mutable should be used or the design should be changed.