Use case:
class A {
static int s_common;
public:
static int getCommon () const { s_common; };
};
Typically this results in an error as:
error: static member function ‘static int A::getCommon()’ cannot have cv-qualifier
This is because const
ness applies only to the object pointed by this
, which is not present in a static
member function.
However had it been allowed, the static
member function's "const"ness could have been easily related to the static
data members.
Why is this feature is not present in C++; any logical reason behind it ?
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.
In C, C++, and D, all data types, including those defined by the user, can be declared const , and const-correctness dictates that all variables or objects should be declared as such unless they need to be modified.
As a general rule: Any non- static member function that does not modify the data members of the object that called it should be declared to be const . That way it will work with constant objects.
cv-qualifiers
affect the function's signature. So you could have:
class A {
static int s_common;
public:
static void getCommon () const { };
static void getCommon () { };
};
Now... how would you call the const
one? There's no const
object to call it on (well, you could call it on a const
object, but that's not the point).
I'm just guessing here, there probably are other reasons. :)
However had it been allowed, the static member function's "const"ness could have been easily related to the static data members.
This is where your question becomes confused. A non-static member function declared as const
still has non-const
access to static data members. The const
only applies to this
(ie: the non-static data members).
It would make no sense for a static member function to use const
in the same way syntactically, yet have a completely different outcome (ie: making access to static data members const
).
Furthermore, static data members are nothing more than class-scoped global variables that have class access controls (public/private/etc) on them. So it doesn't make sense for some functions to have different const
access to them, especially based on their signature.
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