C++ Mutable Keyword



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

Sometimes logic requires to use of only one or two data members as a variable and another one as a constant to handle the data. In that situation, mutability is a very helpful concept to manage classes.

Example

Here is the following example of a mutable keyword in C++.

#include <iostream>
using namespace std;

class Test {
public:
    int a;
    mutable int b;  // 'b' can be modified even for const objects.

    // Explicit constructor to avoid implicit conversions.
    explicit Test(int x = 0, int y = 0) : a(x), b(y) {}

    // Setter for 'a'. Since it modifies the object, it can't be used with const objects.
    void seta(int x = 0) {
        a = x;
    }

    // Setter for 'b'. It can modify 'b' even in const objects because 'b' is mutable.
    // Marked as const to allow it to be called on const objects.
    void setb(int y = 0) const {
        b = y;
    }

    // Display function for the object's state. Marked as const since it doesn't modify the object.
    void disp() const {
        cout << endl << "a: " << a << " b: " << b << endl;
    }
};
int main() {
    const Test t(10, 20);  // Const object 't', 'a' cannot be modified, but 'b' can.

    cout << "Initial values:" << endl;
    cout << "a: " << t.a << " b: " << t.b << "\n";

    // t.a = 30; // Uncommenting this will result in an error as 'a' is part of a const object.

    t.setb(100);  // 'b' can be changed because it is mutable, and setb is now const.
    cout << "After modifying b:" << endl;
    cout << "a: " << t.a << " b: " << t.b << "\n";

    return 0;
}

Output

Here we will get the following output for it.

Initial values:
a: 10 b: 20
After modifying b:
a: 10 b: 100
Updated on: 2024-12-03T21:52:51+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements