Sams Teach Yourself C++ in 21 Days

(singke) #1
Special Classes and Functions 507

22: const int MaxCats = 5; int i;^15
23: Cat *CatHouse[MaxCats];
24:
25: for (i = 0; i < MaxCats; i++)
26: CatHouse[i] = new Cat(i);
27:
28: for (i = 0; i < MaxCats; i++)
29: {
30: cout << “There are “;
31: cout << Cat::HowManyCats;
32: cout << “ cats left!” << endl;
33: cout << “Deleting the one that is “;
34: cout << CatHouse[i]->GetAge();
35: cout << “ years old” << endl;
36: delete CatHouse[i];
37: CatHouse[i] = 0;
38: }
39: return 0;
40: }

There are 5 cats left!
Deleting the one that is 0 years old
There are 4 cats left!
Deleting the one that is 1 years old
There are 3 cats left!
Deleting the one that is 2 years old
There are 2 cats left!
Deleting the one that is 3 years old
There are 1 cats left!
Deleting the one that is 4 years old
On lines 5–16, the simplified class Catis declared. On line 12,HowManyCatsis
declared to be a static member variable of type int.
The declaration of HowManyCatsdoes not define an integer; no storage space is set aside.
Unlike the nonstatic member variables, no storage space is set aside by instantiating a
Catobject because the HowManyCatsmember variable is not in the object. Thus, on line
18, the variable is defined and initialized.
It is a common mistake to forget to declare static member variables and then to forget to
define them. 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 itsAgebecause it is a nonstatic member variable and is
defined each time you make a Catobject, which you do here on line 26.

OUTPUT


LISTING15.1 continued


ANALYSIS
Free download pdf