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.
#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;
}
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++
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
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…