Static functions

Static functions do not belong to an object because they cannot access the data elements of an object. They usually have the task of serving as an interface for the static variables. Among other things, this ensures that variables cannot be manipulated from outside. Static functions have in common with static variables that they belong to the class, but can be used independently of the number or existence of objects.

Syntax

static return-type function-name (parameter1, parameter2, ...) { 
    // code to be executed 
}
Call via object variable

Static functions can be called in the same way as all other functions via the object variable. The object variable and the static function are connected with the point operator.

obj.function-name();
Call via class name

Static functions can also be called directly via the class name. The class name and the static function are connected using the range operator (::).

class-name::function-name();

Example

This is a simple C++ program that defines a class Counter. The class has a static member variable number and a static member function getNumber to access it. The class also has a default constructor which increments the value of number every time an object of the class is created.

In the main function, an object of the class Counter is not created yet, so when the getNumber function is called the first time, it returns the initial value of number, which is 0.

Then, three objects of the class Counter are created (c1, c2, and c3), which increments the value of number to 3. When the getNumber function is called the second time, it returns the updated value of number, which is 3.

#include <iostream>
using namespace std;

class Counter {
public:
    Counter();
    static int getNumber();
private:
    static int number;
};

int Counter::number = 0;

Counter::Counter() {
    number++;
}

int Counter::getNumber() {
    return number;
}

int main() {
    cout << Counter::getNumber() << endl;

    Counter c1, c2, c3;
    cout << Counter::getNumber() << endl;

    return 0;
}
Output
0
3