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.
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) # 3class 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); // 3Tips
- A static method has no "this", so it cannot touch instance fields without being given an object.
- Shared mutable static state is a common source of bugs in multi-threaded code.
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.