Search code examples
c++visual-c++standards

C++ Static member method call on class instance


Here is a little test program:

#include <iostream>

class Test
{
public:
    static void DoCrash(){ std::cout<< "TEST IT!"<< std::endl; }
};

int main()
{
    Test k;
    k.DoCrash(); // calling a static method like a member method...

    std::system("pause");

    return 0;
}

On VS2008 + SP1 (vc9) it compiles fine: the console just display "TEST IT!".

As far as I know, static member methods shouldn't be called on instanced object.

  1. Am I wrong? Is this code correct from the standard point of view?
  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?

Solution

  • 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
    }