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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago