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
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.
Leave a Comment