If you have a member function that accesses only the static data members of a class, you can declare the function static as well. For example:
class SavingsAccount
{
public:
SavingsAccount();
void earnInterest() { total += currentRate * total; }
static void setInterest( float newValue )
{ currentRate = newValue; }
//...
private:
char name[30];
float total;
static float currentRate;
//...
};
Static member functions can be called using the same syntax as that used for accessing static data members. That is:
// Calling a static member function
void main()
{
SavingsAccount myAccount;
myAccount.setInterest( 0.000154 );
SavingsAccount::setInterest( 0.000154 );
}
Since a static member function doesn't act on any particular instance of the class, it has no this pointer. Consequently, a static member function cannot access any of the class's nonstatic data members or call any nonstatic member functions, since doing so would mean implicitly using the this pointer. For example, the function setInterest cannot access the total data member; if it could, which object's value of total would it use?
Static members are useful for implementing common resources that all the objects need, or maintaining state information about the objects. One use of static members is to count how many instances of a class exist at any particular moment. This is done by incrementing a static member each time an object is created and decrementing it each time an object is destroyed. For example:
class Airplane
{
public:
Airplane() { count++; }
static int howMany() { return count; }
~Airplane() { count--; }
private:
static int count;
};
// Initialize static member at file scope
int Airplane::count = 0;
By calling howMany, you can get the number of Airplane objects that exist at any particular time.