Class Variables - heshawacooray/OOP-Heshawa GitHub Wiki

Definition: A class variable, also known as a static member variable, is a variable that is shared among all instances (objects) of a class. Unlike instance variables, class variables are not specific to any one object, but are shared across all objects of that class. They are declared using the static keyword inside the class.

Example code:

class Counter {
public:
    static int count; // Shared among all objects

    Counter() { count++; }
};

int Counter::count = 0;

int main() {
    Counter c1;
    Counter c2;

    cout << "Count: " << Counter::count << endl; // Displays: Count: 2

    return 0;
}