
Posted by Toby Choy on December 08, 1999 at 06:18:56:
Static Class Data
When a data item is defined static in a class, then only one such item is created for the entire class. This is not affected by how many objects there are. When all objects of the same class share a common item or information, a static class should be useful. This is similar to a variable that is defined as static. It is visible only within the class but lasts throughout the entire program. However, a static variable is used to retain information between calls to a function, a stick class member data is used to share information among the objects o a class.
A example of when to use a static class member data is when an object needs to know how many other objects of its class are in the program. A car-racing game for example, where a racecar might want to know how many other cars are still in the game. A static variable would count and indicate a member of the class. All the objects would have access to this variable. The same variable will for all of the objects, therefore the same count.
*****************************************
Class foo
{
private:
static int count; //only one data item for all objects.
//Note: * declaration* only
public:
foo( ) { Count ++; } // increments count when object is created
int getcount( ) { return count; } //returns the count
};
int foo::count; //definition of count
void main ( )
{
foo f1, f2, f3 //create three objects
count << “\ncount is “ << f1.getcount( ); // each object
count << “\ncount is “ << f2.getcount( ); // sees the same
count << “\ncount is “ << f3.getcount( ); // value of count
}
*****************************************************
Outputs: (static data)
Count is 3
Count is 3
Count is 3
Verses ordinary automatic variables: (automatic data)
Count is 1
Count is 1
Count is 1