Sunday, Nov 18th

Last update12:59:40 PM GMT

Static Member Functions

Write e-mail

Now that we already know how static member variables work in a class and how they are shared among all objects of the class, it is time to move on to static member functions. In the previous article, the static member variable was declared as private inside the class myClass. We can anytime initialise the static member variable (under public or private scope) as:


int myClass::my_var = 1;

But in this case where static member variable is private, we can’t access myClass::my_var directly from main(). We can though normally access private static member variables through public member functions. While we could create a normal public member function to access my_var, but then we would need to instantiate an object of the class type to use the function! Surely, we can do better. In this case, the answer to the problem is that we can also make member functions static.

Like static member variables, static member functions are not attached to any particular object. Here is the same example as in last article but with a static member function usage:

class myClass
static int my_var;
static int my_func() { return my_var; }
int myClass::my_var = 1; // initialization
int main()
std::cout << myClass::my_func() << std::endl;

Because static member functions are not attached to a particular object, they can be called directly by using the class name and the scope operator. Like static member variables, they can also be called through objects of the class type, though this is not recommended like in case of static member variables also.

Static member functions have two interesting quirks worth noting.

  • First, because static member functions are not attached to an object, they have no this pointer! This makes sense also when you think about it — the this pointer always points to the object that the member function is working on. Static member functions do not work on any particular object, so the this pointer is not needed.
  • Second, static member functions can only access static member variables. They can not access non-static member variables. This is because non-static member variables must belong to an object, whereas static member functions have no object to work with!

Word of Caution: We should think twice when declaring a class working solely with static member variables and static member functions. Because such a “pure” static class can have potentially same dangers as that associated with global variables (since all the data of such a class can be accessed without instantiating any object).

Share this post

Add comment

Please refrain from using slang or abusive language in the comments.
To avoid waiting for your comment to be published after being reviewed, please log in as a registered user.

Security code

Web Hosting