How do I use static class members in C++?

In C++, static class members are shared among all instances of a class. They can be accessed without creating an instance of the class and are typically used for values that are common to all instances. Static members are useful for maintaining state information that is shared across all instances of a class.

Example of Static Class Members in C++

class Example {
public:
    static int staticValue; // Declaration of static member
    int instanceValue; // Instance member

    Example(int val) : instanceValue(val) {}

    static void setStaticValue(int val) {
        staticValue = val; // Setting value of static member
    }

    static int getStaticValue() {
        return staticValue; // Getting value of static member
    }
};

// Definition of static member
int Example::staticValue = 0;

int main() {
    Example::setStaticValue(10); // Setting static member
    Example obj1(1);
    Example obj2(2);

    std::cout << "Static Value: " << Example::getStaticValue() << std::endl; // Accessing static member
    std::cout << "Instance Value of obj1: " << obj1.instanceValue << std::endl; // Accessing instance member
    std::cout << "Instance Value of obj2: " << obj2.instanceValue << std::endl; // Accessing instance member

    return 0;
}
        

C++ static class members C++ example static functions