Sharing Data Among Objects of the Same Type: Static Member Data ..............
Until now, you have probably thought of the data in each object as unique to that object
and not shared among objects in a class. If you have five Catobjects, for example, each
has its own age, weight, and other data. The age of one does not affect the age of
another.
At times, however, you’ll want to keep track of data that applies to all objects of the
same type. For example, you might want to know how many objects for a specific class
have been created in your program, and how many are still in existence. Static member
variables are variables that are shared among all instances of a class. They are a compro-
mise between global data, which is available to all parts of your program, and member
data, which is usually available only to each object.
You can think of a static member as belonging to the class rather than to the object.
Normal member data is one per object, but static members are one per class. Listing 15.1
declares a Catobject with a static data member,HowManyCats. This variable keeps track
of how many Catobjects have been created. This is done by incrementing the static vari-
able,HowManyCats, with each construction and decrementing it with each destruction.
LISTING15.1 Static Member Data
0: //Listing 15.1 static data members
1:
2: #include <iostream>
3: using namespace std;
4:
5: class Cat
6: {
7: public:
8: Cat(int age):itsAge(age){HowManyCats++; }
9: virtual ~Cat() { HowManyCats--; }
10: virtual int GetAge() { return itsAge; }
11: virtual void SetAge(int age) { itsAge = age; }
12: static int HowManyCats;
13:
14: private:
15: int itsAge;
16: };
17:
18: int Cat::HowManyCats = 0;
19:
20: int main()
21: {
506 Day 15