Special Classes and Functions 511
15
There are 5 cats left!
Deleting the one that is 2 years old
There are 4 cats left!
Deleting the one that is 3 years old
There are 3 cats left!
Deleting the one that is 4 years old
There are 2 cats left!
Deleting the one that is 5 years old
There are 1 cats left!
Deleting the one that is 6 years old
On line 16, the static member variable HowManyCatsis declared to have private
access. Now, you cannot access this variable from nonmember functions, such as
TelepathicFunction()from the previous listing.
Even though HowManyCatsis static, it is still within the scope of the class. As such, any
class function, such as GetHowMany(), can access it, just as member functions can access
any member data. However, for a function outside of a Catobject to call GetHowMany(),
it must have a Catobject on which to call the function.
OUTPUT
ANALYSIS
DOuse static member variables to share
data among all instances of a class.
DOmake static member variables pro-
tected or private if you want to restrict
access to them.
DON’Tuse static member variables to
store data for one object. Static member
data is shared among all objects of its
class.
DO DON’T
Using Static Member Functions ..........................................................................
Static member functions are like static member variables: They exist not in an object but
in the scope of the class. Thus, they can be called without having an object of that class,
as illustrated in Listing 15.4.
LISTING15.4 Static Member Functions
0: //Listing 15.4 static data members
1:
2: #include <iostream>
3:
4: class Cat
5: {
6: public:
7: Cat(int age):itsAge(age){HowManyCats++; }