Each object of a class has its own copy of all the data members of the class. in certain cases, only one copy of a variable should be shared by all objects of a class.
- static class variable
- "Class-wide" data; Property of class, not specific object of class
- Efficient when single copy of data is enough; Only the static variable has to be updated
- May seem like global variables, but have class scope; Only accessible to objects of same class
- Initialized exactly once at file scope
- Exist even if no objects of class exist
- Can be public, private or protected
- Accessing static class variables
- Accessible through any object of class
- public static variables
- Can also be accessed using binary scope resolution operator(::)
- Employee::count
- private static variables
- When no class member objects exist
- Can only be accessed via public static member function
- To call public static member function combine class name, binary scope resolution operator (::) and function name; Employee::getCount()
- static member functions
- Cannot access non-static data or functions
- No this pointer for static functions; static data members and static member functions exist independent of objects
The programs of Figs. 2.25-2.28 demonstrates a private static data member called count and a public static member function called getCount. Figure 2.28 uses function getCount to determine the number of Employee objects currently instantiated.
Figure 2.25:
Employee class definition with a static data member to track the number Employee objects in memory.
|
Figure 2.26:
Employee class member-function definitions. (part 1 of 2)
|
Figure 2.27:
Employee class member-function definitions. (part 2 of 2) and static data member tracking the number of objects of a class. (part 1 of 2)
|
Figure 2.28:
static data member tracking the number of objects of a class. (part 2 of 2)
|
2004-12-28