In Chapter 6, we described two types of variables: automatic and static. Recall that if a local variable of a function is static, it exists between function calls. Similar to static variables, a class can have static members, functions, or variables.
If a function of a class is static, in the class definition it is declared using the keyword static in its heading.
If a member variable of a class is static, it is declared using the keyword static,
A public static member, function, or variable of a class can be accessed using the class name and the scope resolution operator.
In C++, a static class member is a member of a class that belongs to the class itself, rather than to any particular instance of the class. A static member is shared by all objects of the class and can be accessed using the class name, without needing an object of the class.
Here's an example of a static class member:
class MyClass { public: static int count; // static class member MyClass() { count++; // increment count on each object creation } }; int MyClass::count = 0; // initialize the static member outside the class definition int main() { MyClass obj1; MyClass obj2; MyClass obj3; cout << MyClass::count << endl; // prints "3" return 0; }
In this example, we have defined a static class member count
in the MyClass
class. We have also defined a constructor that increments count
on each object creation. Finally, we have initialized the static member outside the class definition.
In the main
function, we create three objects of the MyClass
class, which results in count
being incremented three times. We then print the value of count
using the class name, without needing an object of the class.
Static class members are useful when you need to share data or behavior among all objects of a class. They can also be used to maintain a count of objects of a class, as shown in this example.