C++ mutable keyword with example

C++ mutable keyword

Mutable is also one of the storage class specifier in C++, along with the mutable, there are auto, register, static and extern are the storage class specifiers in C++. There is another storage class specifier in C is typedef.

Why do we need mutable keywords? What is the use of Mutable Keyword?

Sometimes there is a requirement to modify one or more data members of class/struct through const function even though you don’t want the function to update other members of class/struct.
A mutable keyword is used to perform the modifications on the const variables.

Below is the example where the use of mutable can be useful. Suppose we have the vehicle class, the features of the vehicle are same where ever you go. Suppose we want to sell the vehicle, we need to change the owner’s name and the price. At this scenario, we have to create the variable with the storage class mutable.

The output of the above program is:

Closely observe the output of the above program. The values of pcchOwner and iPrice data members are changed from const function because they are declared as mutable.

The mutable keyword is mainly used to allow the programmer to modify the const data member to the modified one. Adding mutable to a variable allows a const pointer to change members.
mutable is particularly useful if most of the members should be constant but a few need to be updateable. Data members declared as mutable can be modified even though they are the part of an object declared as const.