Static methods

Just as a class's data can be made static, so can its methods.


In this respect they act like global functions and are accessed like object members of a class.


Since static methodsĀ are members of the whole class and not of any instance of an object, they can:

  • only use a class's static data
  • not use non-static members
  • not use the keyword this, as it uses a pointer to an object
  • be called independently, even if no object exists
  • be accessed using the scope resolution operator ::


If access to a class's private data member is required, we would normally write a public accessor (get) method. However, this would require instantiation of a class object to access the function. Therefore in the case of static data, we write a public static method to return the static data.


Compile & Run:

In the beginning there were 0 Humanoids!
But they bred...
Humanoid #0 created!
Humanoid #1 created!
Humanoid #2 created!
Humanoid #3 created!
Creating 4 Humanoids!
So we killed them...
Humanoid #3 destroyed!
Humanoid #2 destroyed!
Humanoid #1 destroyed!
Humanoid #0 destroyed!



Or even simpler, not even creating any objects and just using the static method:

Accessing static method 1 times
Accessing static method 2 times
Accessing static method 3 times
Accessing static method 4 times
Accessing static method 5 times
Accessing static method 6 times

Leave a Reply