Only one copy of a static member of a class is created, regardless of how many instances (objects) of that class are instantiated. This single copy is shared among all objects of the class. The static member belongs to the class itself, not to any individual object
. To summarize:
- When a member of a class is declared static, there is exactly one copy of that member in memory.
- This static member is shared by all instances of the class.
- It can be accessed using the class name and the scope resolution operator (:: in C++), without needing to create an object.
- Static members are commonly used for data or functions that should be common to all objects, such as counters tracking the number of instances created.
For example, in C++:
cpp
class MyClass {
public:
static int count;
MyClass() { count++; }
};
int MyClass::count = 0; // one-time initialization
int main() {
MyClass a, b;
std::cout << MyClass::count; // Outputs 2, the number of instances created
}
Here, count
is a static member with only one copy shared by all objects
. This principle applies similarly in other languages like C# and JavaScript, where static members belong to the class itself rather than any instance