Here’s a minimal working example:
A.h:
class A{
static int a_member_function();
};
A.cpp
#include "A.h"
int A::a_member_function(){return 5;}
int main(){ return 1;}
This code compiles and runs, but, it seems to me that:
static int A::a_member_function(){return 5;}
could just as easily be used to define the static member function of class A. Indeed, it seems like it could actually be rather useful to have this requirement, since it would remind the reader of the .cpp file that a_member_function is static.
However, this clearly doesn’t work:
error: cannot declare member function ‘static int A::a_member_function()’ to have static linkage [-fpermissive]
So why doesn’t it work? What’s the reasoning behind this decision?
The reason behind is C++ spirit to try and minimize the number of its keywords and keep backward compatibility with C:
staticin that position has an entirely different meaning.It all predates back to C. “static” functions in C are functions that are unique to a compilation unit (a .c file). They can’t be accessed by other compilation units (it’s one way to have encapsulation in C). This usage is still valid in C++. You can also do the same for global variables to limit their scope.
Though, in C++ you also want to declare member functions as
staticfor a different reason: those functions belong to class but do not require and instance of said class to run (I bet you know that already, I am just trying to be complete).Defining a member function as
staticwould lead to a contradiction: that function must be accessed outside of its translation unit.There’s another case of keyword reuse between C and C++, the
autokeyword in C++11, but it is less likely to be a problem.Note:
The same thing happens with the
virtualkeyword which is present in the declaration and not the definition.