Why can a const member function modify a static data member?

It’s the rule, that’s all. And for good reason.

The const qualifier on a member function means that you cannot modify non-mutable non-static class member variables.

By way of offering some rationalisation, the this pointer in a const qualified member function is a const type, and this is inherently related to an instance of a class. static members are not related to a class instance. You don’t need an instance to modify a static member: you can do it, in your case, by writing A::a = 10;.

So, in your first case, think of a = 10; as shorthand for A::a = 10; and in the second case, think of it as shorthand for this->a = 10;, which is not compilable since the type of this is const A*.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)