Sams Teach Yourself C++ in 21 Days

(singke) #1
Special Classes and Functions 513

15


The static member variable HowManyCatsis declared to have private access on
line 14 of the Catdeclaration. The public accessor function,GetHowMany(),is
declared to be both public and static on line 11.
Because GetHowMany()is public, it can be accessed by any function, and because it is
static, no need exists to have an object of type Caton which to call it. Thus, on line 41,
the function TelepathicFunction()is able to access the public static accessor, even
though it has no access to a Catobject. You should note, however, that the function is
fully qualified when it is called, meaning the function call is prefixed with the class name
followed by two colons:
Cat::TelepathicFunction()
Of course, you could also have called GetHowMany()on the Catobjects available in
main(), the same as with any other accessor functions.

ANALYSIS

Static member functions do not have a thispointer. Therefore, they cannot
be declared const. Also, because member data variables are accessed in
member functions using the thispointer, static member functions cannot
access any nonstatic member variables!

NOTE


Static Member Functions
You can access static member functions by calling them on an object of the class the same
as you do any other member function, or you can call them without an object by fully
qualifying the class and object name.
Example
class Cat
{
public:
static int GetHowMany() { return HowManyCats; }
private:
static int HowManyCats;
};
int Cat::HowManyCats = 0;
int main()
{
int howMany;
Cat theCat; // define a cat
howMany = theCat.GetHowMany(); // access through an object
howMany = Cat::GetHowMany(); // access without an object
}
Free download pdf