< Previous | Contents | Next >

Calling Static Member Functions

After I instantiate three Critter objects in main(), I reveal the total number of critters again with the following line, which displays 3.

cout << Critter::GetTotal() << "\n\n";

To properly identify the static member function, I had to qualify it with Critter::. To call a static member function from outside of its class, you must qualify it with its class name.

274 Chapter 8 n Classes: Critter Caretaker


Hi n t

image

You can also access a static member function through any object of the class. Assuming that

crit1 is a Critter object, I could display the total number of critters with the following line:

cout << crit1.GetTotal() << "\n\n";

image


Because static member functions exist for the entire class, you can call a static member function without any instances of the class in existence. And just as with private static data members, private static member functions can only be accessed by other member functions of the same class.