Static Method Called using NULL Pointer in C++


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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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!
}
#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.

1
((Foo*)0)->foo();
((Foo*)0)->foo();

The cast is just to please the compiler but you can just write it in a more acceptable way:

1
Foo::foo();
Foo::foo();

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
227 words
Last Post: Square Root Under BASH Shell
Next Post: Less Known HTML Tags

The Permanent URL is: Static Method Called using NULL Pointer in C++

Leave a Reply