Similar to static member variables, C++ also allows us to create static member functions. For example,
#include <iostream>
class Counter
{
static inline int s_count{0};
public:
static int next()
{
return ++s_count;
}
static int prev();
};
int Counter::prev()
{
return --s_count;
}
int main(int argc, char const *argv[])
{
std::cout << Counter::next() << "\n";
std::cout << Counter::next() << "\n";
std::cout << Counter::prev() << "\n";
std::cout << Counter::prev() << "\n";
return 0;
}There are two static member functions next and prev. next is defined inside the class and prev outside (for demonstration purposes). When we defined static member function outside, we do require to put static there.
Few things to note about static member functions:
- They can access other static members.
- They can’t access non-static data members. This is obvious that non-static data members are for objects and static members only belong to classes.
- Similar to above point, static member functions don’t have
thispointer because static member functions are not attached to any class object. - Although, static member functions can be accessed in class objects but it is not recommended (why? maybe because calling static methods on object creates confusion if non-static member function is called or static.).