Sams Teach Yourself C++ in 21 Days

(singke) #1
On line 8, the constructor for Catincrements the static member variable. The destructor
decrements it on line 9. Thus, at any moment,HowManyCatshas an accurate measure of
how many Catobjects were created but not yet destroyed.
The driver program on lines 20–40 instantiates five Cats and puts them in an array. This
calls five Catconstructors, and, thus,HowManyCatsis incremented five times from its ini-
tial value of 0.
The program then loops through each of the five positions in the array and prints out the
value of HowManyCatsbefore deleting the current Catpointer on line 36. The printout
reflects that the starting value is 5 (after all, 5 are constructed), and that each time the
loop is run, one fewer Catremains.
Note that HowManyCatsis public and is accessed directly by main(). There is no reason
for you to expose this member variable in this way. In fact, it is preferable to make it pri-
vate along with the other member variables and provide a public accessor method, as
long as you will always access the data through an instance of Cat. On the other hand, if
you want to access this data directly, without necessarily having a Catobject available,
you have two options: Keep it public, as shown in Listing 15.2, or provide a static mem-
ber function, as discussed later in today’s lesson.

LISTING15.2 Accessing Static Members Without an Object
0: //Listing 15.2 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: void TelepathicFunction();
21:

508 Day 15

Free download pdf