Skip to content

Mutable

Example

cpp
#include <iostream>

class A {
public:
    int a;
    mutable int b;

    void change() const
    {
        b = 10; // this is allowed because b is mutable
    }

};

int main()
{
    A a;
    a.a = 5;
    a.b = 5;
    std::cout << a.a << std::endl;
    std::cout << a.b << std::endl;
    a.change();
    std::cout << a.a << std::endl;
    std::cout << a.b << std::endl;
}

Explanation

mutable is a keyword that allows you to change a variable in a const function.

References