Why can a static member function only be declared static inside the class definition and not also in its own definition?

mr_T picture mr_T · Sep 22, 2014 · Viewed 12.3k times · Source

While implementing a class for creating/updating boxes on the screen, I wanted to add a static member function that makes sure no currently visible boxes overlap (taking its information from a static pointer array to all currently visible boxes)

My initial code had the following structure:

class Box
{
public:
    // ...
    static void arrangeOverlappingBoxes();
};

static void Box::arrangeOverlappingBoxes()
{
    // ...
}

I was quite surprised that this generated an error C2724: 'static' should not be used on member functions defined at file scope.

With some trial, google and error, I figured out that my function definition should lose the keyword static, i.e. it should be

void Box::arrangeOverlappingBoxes()
{
    // ...
}

Yet I have no clue what the rationale behind this could be. It appears to be so asymetric and confusing to have a different function header for its declaration in the class definition and its own definition. Is there any reason for this?

Answer

MichaelCMS picture MichaelCMS · Sep 22, 2014

Your class definition (in the header file) will provide the function with whatever propreties are necessary :

  • static
  • inlined
  • virtual

Considering that every further object will look at your class definition using the .h then it makes sense that these properties to be defined there.

Furthermore, each function from the class will mentain it's property in the derived classes (for example you need to declare the destructor virtual only in your base class, every subsequent inheritance will take the destructor as virtual).

It makes no sense to redeclare these properties in your implementation body .

Having to declare function proprieties in both .h and .cpp files would actually lead to allot of problems. Imagine this scenario : you declare a function as virtual in a .h file, and as static in the .cpp file. What will the compiler make that function ? virtual or static ? (or more likely a compile error , but the compiler error will just urge you to match in your .cpp file the declaration in the header. You cannot overload a function according to "static" or "virtual").