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

Select a Random Element from a Stream

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

1 day ago

Estimate π Using Monte Carlo Method

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

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago