Search code examples
c++visual-c++staticconstants

Why can't a static member function have a cv-qualifier?


This is the error:

error: static member function ‘static void myClass::myfunct()’ cannot have cv-qualifier

Can someone please explain this error and why const cannot be used.

#include<iostream>
class myClass{      
   static void myfunct() const 
   { 
     //do something
   }
};

int main()
{
   //some code
   return 0;
}

Solution

  • Worth quoting the standard here

    9.4.1 Static member functions

    2) [ Note: A static member function does not have a this pointer (9.3.2). —end note ] A static member function shall not be virtual. There shall not be a static and a non-static member function with the same name and the same parameter types (13.1).

    A static member function shall not be declared const, volatile, or const volatile.

    static functions have no this parameter. They need no cv-qualifiers.

    See this answer by James McNellis

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