Categories: C++

Mutable keyword in C++

Mutable data members are those whose values can be changed in runtime even if the object’s type is constant. It is the polar opposite of constant.

It is sometimes necessary to modify one or more data members of a class or struct using a const function, even if you do not want the function to update other members of the class or struct. The mutable keyword makes it simple to complete this task.

Example:
#include <iostream>
using namespace std;
class Coderz {
   public:
      int a;
   mutable int b;
   Coderz(int x=0, int y=0) {
      a=x;
      b=y;
   }
   void seta(int x=0) {
      a = x;
   }
   void setb(int y=0) {
      b = y;
   }
   void disp() {
      cout<<endl<<"a: "<<a<<" b: "<<b<<endl;
   }
};
int main() {
   const Coderz t(10,20);
   cout<<t.a<<" "<<t.b<<"\n";
   // t.a=30; //Error occurs because a can not be changed, because object is constant.
   t.b=100; //b still can be changed, because b is mutable.
   cout<<t.a<<" "<<t.b<<"\n";
   return 0;
}
Output:
10 20
10 100

If we uncomment the commented statements, then an error occurs, i.e,

/tmp/V7dAvdWEIa.cpp: In function 'int main()':
/tmp/V7dAvdWEIa.cpp:24:7: error: assignment of member 'Coderz::a' in read-only object
   24 |    t.a=30; //Error occurs because a can not be changed, because object is constant.
      |    ~~~^~~

Note: also read about const keyword in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

3 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

4 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

4 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

5 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

5 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

5 months ago