views:

4381

answers:

3

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 diplay "TEST IT!".

As far as i know, static member methods shouldn't be called on instancied 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?

+1  A: 

static methods can be called also using an object of the class, just like it can be done in Java. Nevertheless, you shouldn't do this. Use the scope operator like Test::DoCrash(); Maybe you think of namespaces:

namespace Test {
    void DoCrash() {
        std::cout << "Crashed!!" << std::endl;
    }
};

which can only be called by Test::DoCrash(); from outside that namespace if the function is not imported explicitly using a using directive/declaration into the scope of the caller.

Johannes Schaub - litb
Yes, i know i should do this, that's why i ask why the other way (calling like a member) is allowed/not forbidden. :)
Klaim
+9  A: 

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.

[Example:
class process {
public:
   static void reschedule();
};
process& g();
void f()
{
   process::reschedule(); // OK: no object necessary             
   g().reschedule(); // g() is called
}  —end example]
David Rodríguez - dribeas
fixed the formatting of the quote. hope you don't mind
Johannes Schaub - litb
Thanks, I don't really know that much of StakOverflow formatting tags.
David Rodríguez - dribeas
A: 

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.

jab