mutable Storage Class
Sometimes there is a requirement to modify one or more data members of class/struct through the const function even though you don’t want the function to update other members of class/struct. This task can be easily performed by using the mutable keyword. The keyword mutable is mainly used to allow a particular data member of a const object to be modified.
When we declare a function as const, this pointer passed to the function becomes const. Adding a mutable to a variable allows a const pointer to change members.
Properties of mutable Storage Class
The mutable specifier does not affect the linkage or lifetime of the object. It will be the same as the normal object declared in that place.
Example of mutable Storage Class
C++
// C++ program to illustrate the use of mutalbe storage // class specifiers #include <iostream> using std::cout; class Test { public : int x; // defining mutable variable y // now this can be modified mutable int y; Test() { x = 4; y = 10; } }; int main() { // t1 is set to constant const Test t1; // trying to change the value t1.y = 20; cout << t1.y; // Uncommenting below lines // will throw error // t1.x = 8; // cout << t1.x; return 0; } |
20
Storage Classes in C++ with Examples
C++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specify the storage class for a variable.
Syntax
To specify the storage class for a variable, the following syntax is to be followed:
storage_class var_data_type var_name;
C++ uses 6 storage classes, which are as follows:
- auto Storage Class
- register Storage Class
- extern Storage Class
- static Storage Class
- mutable Storage Class
- thread_local Storage Class
Below is a detailed explanation of each storage class: