Consider:
// In Vector2.h
class Vector2
{
public:
// returns the degrees in radians
static double calcDir(double x, double y);
}
// In Vector2.cpp
double Vector2::calcDir(double x, double y)
{
double rad = ...;
return rad;
}
Why isn’t the keyword static required in the signature in Vector2.cpp? When I try this, it produces an error:
static double Vector2::calcDir(double x, double y)
It seems inconsistent to me. All other parts of the method signature are required to be repeated in the .cpp file (return type, method name (duh), names and types of args, const-ness). I don’t like not knowing at a glance whether a method is static or not (when looking at the implementation).
Is there a reason this is not only not required, but forbidden?
It’s because
statichas a special meaning when used in a class definition. In a class definition it identifies the function as a static member function which means it doesn’t operate on a class instance but can be called independently.Outside of a class
staticgives a function internal linkage but this is illegal on (even static) member functions because class members must have the same linkage as the class of which they are a member (almost always external, and certainly external in cases where you can defined member functions outside of the class definition).From a language point of view, the declaration of members inside a class definition follows one set of language rules where
statichas its special class meaning. Outside of a class definition, all function definitions – members and non-members – follow the same set of rules wherestatichas it’s other meaning which is not valid for members of classes with external linkage.