C++ Static member method call on class instance

Solution 1:

The standard states that it is not necessary to call the method through an instance, that does not mean that you cannot do it. There is even an example where it is used:

C++03, 9.4 static members

A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object-expression is evaluated.

class process {
public:
   static void reschedule();
};

process& g();

void f()
{
   process::reschedule(); // OK: no object necessary             
   g().reschedule(); // g() is called
}

Solution 2:

Static functions doesn´t need an instanciated object for being called, so

k.DoCrash();

behaves exactly the same as

Test::DoCrash();

using the scope resolution operator (::) to determine the static function inside the class.

Notice that in both case the compiler doesn´t put the this pointer in the stack since the static function doesn't need it.

Solution 3:

2) If it's correct, why is that? I can't find why it would be allowed, or maybe it's to help using "static or not" method in templates?

It's potentially useful in several scenarios:

  • [the '"static or not" method in templates' you suggest:] when many types could have been specified to a template, and the template then wants to invoke the member: the types providing a static function can be called using the same notation as a member function - the former may be more efficient (no this pointer to pass/bind), while the latter allows polymorphic (virtual) dispatch and use of member data

  • minimising code maintenance

    • if a function evolves from needing instance-specific data to not needing it - and is therefore made static to allow easy instance-free use and prevent accidental use of instance data - all the points of existing client usage don't need to be labouriously updated

    • if the type's changed the var.f() invocation continues to use the var type's function, whereas Type::f() may need manual correction

  • when you have an expression or function call returning a value and want to invoke the (potentially or always) static function, the . notation may prevent you needing to use decltype or a supporting template to get access to the type, just so you can use the :: notation

  • sometimes the variable name is just much shorter, more convenient, or named in a more self-documenting way