< previous page page_319 next page >

Page 319
LISTING 20.1 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
32:          cout << Cat::HowManyCats;
33:          cout <<  cats left!\n;
34:          cout << Deleting the one which is ;
35:          cout << CatHouse[i]->GetAge();
36:          cout <<  years old\n;
37:          delete CatHouse[i];
38:          CatHouse[i] = 0;
39:       }
40:       return 0;
41:    }

Output:
There are 5 cats left!
Deleting the one which is 0 years old
There are 4 cats left!
Deleting the one which is 1 years old
There are 3 cats left!
Deleting the one which is 2 years old
There are 2 cats left!
Deleting the one which is 3 years old
There are 1 cats left!
Deleting the one which is 4 years old
Analysis: On lines 517 the simplified class Cat is declared. On line 12, HowManyCats is declared to be a static member variable of type int.
The declaration of HowManyCats does not define an integer; no storage space is set aside. Unlike the non-static member variables, no storage space is set aside for static members as a result of instantiating a Cat object, because the HowManyCats member variable is not in the object. Therefore, on line 19 the variable is defined and initialized.
It is a common mistake to forget to define the static member variables of classes. Don't let this happen to you! Of course, if it does, the linker will catch it with a pithy error message such as the following:
undefined symbol Cat::HowManyCats
You don't need to do this for itsAge because it is a nonstatic member variable and is defined each time you make a Cat object, which is done here on line 27.
The constructor for Cat increments the static member variable on line 8. The destructor decrements it on line 9. Thus, at any moment, HowManyCats has an accurate measure of how many Cat objects were created but not yet destroyed.
The driver program on lines 2141 instantiates five Cats and puts them in an array. This calls five Cat constructors; thus HowManyCats is incremented five times from its initial value of 0.

 
< previous page page_319 next page >

If you like this book, buy it!