Static Member Functions

Static member functions can only access global variables and functions and static members of the class they belong to. They cannot be virtual, const or volatile and they can’t have a this pointer. Further, they cannot be overloaded as non-static. Substantially static member functions can be useful when you want to be sure that only global and static data and functions (i.e shared among all objects of the class) are affected.

Example


#include <iostream>
#include <string>
using namespace std;

class Person
{
     static int personsNumber;   // variable declaration
     string name;
public:
     Person(string aName)
     {
           name = aName;
           increasePersonsNumber();
     }

     ~Person()
     {
           decreasePersonsNumber();
     }

     int getPersonsNumber()
     {
           return personsNumber;
     }

     static void increasePersonsNumber()  // can only access personsNumber
     {
        personsNumber++;
     }

     static void decreasePersonsNumber()  // can only access personsNumber
     {
        personsNumber--;
     }
};

int Person::personsNumber;     // variable definition

int main()
{   
     Person obj1("Mike");
     Person obj2("Sam");
     cout << "The number of persons is: " << obj2.getPersonsNumber() << endl;
}

Output

The number of persons is: 2