C++ – Why can a const member function modify a static data member

cc++11constantsfunctionstatic

In the following C++ program, modifying a static data member from a const function is working fine:

class A 
{
  public:   
    static int a; // static data member

    void set() const
    {
        a = 10;
    }
};

But modifying a non-static data member from a const function does not work:

class A 
{
  public:   
    int a; // non-static data member

    void set() const
    {
        a = 10;
    }
};

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

Best Answer

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*.