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

#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