C++ - Why static member function can't be created with 'const' qualifier
When you apply the const
qualifier to a nonstatic member function, it affects the this
pointer. For a const-qualified member function of class C
, the this
pointer is of type C const*
, whereas for a member function that is not const-qualified, the this
pointer is of type C*
.
A static member function does not have a this
pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.
I agree with your question, but unfortunately the C++ is designed that way. For example:
class A {
int i; //<--- accessed with 'this'
static int s; //<---- accessed without 'this'
public:
static void foo () const // <-- imaginary const
{}
};
As of today, the const
is considered in context of this
. In a way, it's narrow. It can be made broader by applying this const
beyond this
pointer.
i.e. the "proposed" const
, which may also apply to static
functions, will restrict the static
members from any modification.
In the example code, if foo()
can be made const
, then in that function, A::s
cannot be modified. I can't see any language side effects, if this rule is added to standard. On the contrary, it's amusing that why such rule doesn't exist!