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.
A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.
Static Function Members By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.
You cannot have static and nonstatic member functions with the same names and the same number and type of arguments. Like static data members, you may access a static member function f() of a class A without using an object of class 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; } };
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 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With