14.4 Static Member Variables
Suppose you want to keep a running count of
the number of stacks in use at any given time. One way to do this is
to create a global variable stack_count that is
incremented in the stack constructor and decremented in the
destructor:
int stack_count = 0; // Number of stacks currently in use
class stack {
private:
int count; // Number of items in the stack
// ... member variables
public:
int data_count; // Number of items in the stack
// ... member variables
stack( ) {
// We just created a stack
++stack_count;
count = 0;
}
~stack( ) {
// We now have one less stack
--stack_count;
}
// ... other member functions
};
Note that stack_count is a single global variable.
No matter how many different stacks you create, there is one and only
one stack_count.
Although this system works, it has some drawbacks. The definition of
the class stack contains everything about the
stack, except the variable stack_count. It would
be nice to put stack_count in the class, but if
you define it as a member variable, you'll get a new
copy of stack_count each time you declare a
stack class variable.
C++ has a special modifier for member variables:
static. This tells C++ that one and only one
variable is to be defined for the class:
class stack {
private:
static int stack_count; // Number of stacks currently in use
int count; // Number of items in the stack
// ... member variables
public:
stack( ) {
// We just created a stack
++stack_count;
count = 0;
}
~stack( ) {
// We now have one less stack
--stack_count;
}
// ... other member functions
};
This new version looks almost the same as the global variable
version. There is, however, one thing missing: the initialization of
stack_count. This is done with the statement:
int stack::stack_count = 0; // No stacks have been defined
The difference between static and nonstatic member variables is that
member variables belong to the object, while static member variables
belong to the class. Thus if you create three
stacks, you get three copies of the ordinary
member variable data_count. However, since there
is only one definition of the class, only one
stack_count is created.
So if you have:
stack a_stack;
stack b_stack;
a_stack.stack_count is the same as
b_stack.stack_count. There is only one
stack_count for the class
stack. C++ allows you to access static member
variables using the syntax:
<class>::<variable>
Thus you can get to stack_count with the statement:
std::cout << "The number of active stacks is " <<
stack::stack_count << '\n';
(Or at least you could if stack_count was not
private.)
You can use the dot notation
(a_stack.stack_count), but this is considered poor
programming style. That's because it implies that
stack_count belongs to the object
a_stack. But because it's
static, the variable belongs to the class
stack.
|