Possible Duplicate:
C++ - Why static member function can’t be created with ‘const’ qualifier
Was curious to know the reason why static member functions cant be declared as const or volatile or const volatile ?
#include<iostream>
class Test
{
static void fun() const
{ // compiler error
return;
}
};
A 'const member function' is not allowed to modify the object it is called on, but static member functions are not called on any object. It is used directly by scope resolution operator. Thus having a const static member function makes no sense, hence it is illegal.
A static member function cannot be declared with the keywords virtual , const , volatile , or const volatile . A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared.
The volatile keyword, like const, is a type qualifier. These keywords can be used by themselves, as they often are, or together in variable declarations.
static const : “static const” is basically a combination of static(a storage specifier) and const(a type qualifier). Static : determines the lifetime and visibility/accessibility of the variable.
The cv-modifiers of the member functions correspond to the qualification of the hidden this
parameter.
static
functions have no this
parameter. Therefore, they need no cv-qualifiers. So it was decided (IMHO rightly, as otherwise, it would have no meaning) to disallow them on static
functions.
BTW static
member functions can't also be virtual
, pure (=0
), deleted, defaulted, &&
etc.
Because that's what the standard says:
2) [ Note: A static member function does not have a this pointer (9.3.2). —end note ] A
static
member function shall not bevirtual
. There shall not be astatic
and a non-static
member function with the same name and the same parameter types (13.1). A static member function shall not be declaredconst
,volatile
, orconst volatile
. (emphasis mine)
The reason for this is that a const
(or volatile
or virtual
) static
method wouldn't make sense (in the traditional sense, see below). For example, const
implies you can't modify the object's members, but in the case of statics, there's no object to talk about.
You could argue that a const
static
could apply to other static
members, but this option was regarded as pointless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With