Static member functions (C++ only)

You cannot have static and nonstatic member functions with the same names and the same number and type of arguments.

Like static data members, you may access a static member function f() of a class A without using an object of class A.

A static member function does not have a this pointer. The following example demonstrates this:

#include <iostream>
using namespace std;

struct X {
  int i;
  static int si;
  void set_i(int arg) { i = arg; }
  static void set_si(int arg) { si = arg; }

  void print_i() {
    cout << "Value of i = " << i << endl;
    cout << "Again, value of i = " << this->i << endl;

  static void print_si() {
    cout << "Value of si = " << si << endl;
//    cout << "Again, value of si = " << this->si << endl;


int X::si = 77;       // Initialize static data member

int main() {
  X xobj;

  // static data members and functions belong to the class and
  // can be accessed without using an object of class X

The following is the output of the above example:

Value of i = 11
Again, value of i = 11
Value of si = 77
Value of si = 22

The compiler does not allow the member access operation this->si in function A::print_si() because this member function has been declared as static, and therefore does not have a this pointer.

You can call a static member function using the this pointer of a nonstatic member function. In the following example, the nonstatic member function printall() calls the static member function f() using the this pointer:

#include <iostream>
using namespace std;

class C {
  static void f() {
    cout << "Here is i: " << i << endl;
  static int i;
  int j;
  C(int firstj): j(firstj) { }
  void printall();

void C::printall() {
  cout << "Here is j: " << this->j << endl;

int C::i = 3;

int main() {
  C obj_C(0);

The following is the output of the above example:

Here is j: 0
Here is i: 3

A static member function cannot be declared with the keywords virtual, const, volatile, or const volatile.

A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared. Suppose a static member function f() is a member of class X. The static member function f() cannot access the nonstatic members X or the nonstatic members of a base class of X.

Related information