Static and instance members

An instance field exists once per object. A static field exists once for the whole class and is shared by every object.

Time O(1)Space one shared copyCode C++, Python and C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Static members belong to the class itself. You reach them through the class name, Visitor.Count, and they exist even before any object is created.

Code

class Visitor {
public:
    static inline int count = 0;   // one copy, shared by the class
    string name;                   // one copy per object
    Visitor(string name) : name(name) { count++; }
};

int main() {
    Visitor a("Asha");
    Visitor b("Ravi");
    Visitor c("Meera");
    cout << Visitor::count << "\n";   // 3
}
class Visitor:
    count = 0  # one copy, shared by the class

    def __init__(self, name: str):
        self.name = name  # one copy per object
        Visitor.count += 1

a = Visitor("Asha")
b = Visitor("Ravi")
c = Visitor("Meera")
print(Visitor.count)  # 3
class Visitor {
    public static int Count;      // one copy, shared by the class
    public string Name;           // one copy per object
    public Visitor(string name) { Name = name; Count++; }
}

var a = new Visitor("Asha");
var b = new Visitor("Ravi");
var c = new Visitor("Meera");
Console.WriteLine(Visitor.Count);   // 3

Tips

In the .NET library

A static class such as Math or Console cannot be instantiated at all. In a web app, static fields are shared across every request, so prefer dependency injection with a singleton lifetime.