This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.
Let see the below code, where I am incrementing the mutable variable in a const member function. If you will remove the mutable keyword you will get a compiler error.
#include <iostream>
using namespace std;
class Demo
{
public:
Demo():m_accessCount(0)
{
}
int GetData() const
{
return (++m_accessCount);
}
private:
mutable int m_accessCount;
};
int main()
{
Demo obj;
cout << obj.GetData()<<endl;
return 0;
}
Answer:
This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.
Let see the below code, where I am incrementing the mutable variable in a const member function. If you will remove the mutable keyword you will get a compiler error.
Output: 1
need an explanation for this answer? contact us directly to get an explanation for this answer