I am studying C++ and I read that: If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function. But the following code compiled without any error or warning by gcc. (It is not a real-world code example, I just wrote it to test the mutable keyword)
class M
{
public:
M(){x=10;};
int getX() {x++; return x;};
private:
mutable int x;
};
int main()
{
M xx;
std::cout << xx.getX() << std::endl;
}
Shouldn't I declare getX as const?
Edit 1 (ForEver's answer makes the things more clear), the following code will not be compiled:
class M
{
public:
M(){x=10;};
int getX() const {x++; return x;};
private:
int x;
};
int main()
{
M xx;
std::cout << xx.getX() << std::endl;
}
const
before learningmutable
. – Drew Dormann