The static methods in OOP (Object Oriented Programming) can be treated as ‘global methods’ for that class. It means that every instances (objects) of class share the same method/variables (only 1 copy in memory).
Inside static methods, you can only reference to static attributes. There is only 1 copy of a static variable in memory because that static attribute is shared among all instances of the class.
Therefore, it is easy to understand that in C++, you don’t need a instance to access static attributes and methods. You can call static methods and attributes using NULL pointer.
#include <iostream>
class Foo {
public:
static void foo() {
std::cout << "foo()" << std::endl;
}
const static int x = 123;
};
int main(void) {
Foo * foo = NULL;
foo->foo(); //=> WTF!?
std::cout << foo->x;; // still works!
return 0; // Ok!
}
In fact, the following NULL pointer deference is also OK.
((Foo*)0)->foo();
The cast is just to please the compiler but you can just write it in a more acceptable way:
Foo::foo();
–EOF (The Ultimate Computing & Technology Blog) —
210 wordsLast Post: Square Root Under BASH Shell
Next Post: Less Known HTML Tags