The mutable storage class in C++

C++Server Side ProgrammingProgramming

The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const. You cannot use the mutable specifier with names declared as static or const, or reference members.

In the following example

class A
   A() : x(4), y(5) { };
   mutable int x;
   int y;

int main()
   const A var2;
   var2.x = 345;
   // var2.y = 2345;

the compiler would not allow the assignment var2.y = 2345 because var2 has been declared as const. The compiler will allow the assignment var2.x = 345 because A::x has been declared as mutable.

Updated on 10-Feb-2020 12:34:28