static
MembersAs with any other member function, we can define a static
member function inside or outside of the class body. When we define a static
member outside the class, we do not repeat the static
keyword. The keyword appears only with the declaration inside the class body:
void Account::rate(double newRate)
{
interestRate = newRate;
}
As with any class member, when we refer to a class static
member outside the class body, we must specify the class in which the member is defined. The static
keyword, however, is used only on the declaration inside the class body.
Because static
data members are not part of individual objects of the class type, they are not defined when we create objects of the class. As a result, they are not initialized by the class’ constructors. Moreover, in general, we may not initialize a static
member inside the class. Instead, we must define and initialize each static
data member outside the class body. Like any other object, a static
data member may be defined only once.
Like global objects (§ 6.1.1, p. 204), static
data members are defined outside any function. Hence, once they are defined, they continue to exist until the program completes.
We define a static
data member similarly to how we define class member functions outside the class. We name the object’s type, followed by the name of the class, the scope operator, and the member’s own name:
// define and initialize a static class member
double Account::interestRate = initRate();
This statement defines the object named interestRate
that is a static
member of class Account
and has type double
. Once the class name is seen, the remainder of the definition is in the scope of the class. As a result, we can use initRate
without qualification as the initializer for interestrate
. Note also that although initRate
is private
, we can use it to initialize interestRate
. Aswith any other member definition, a static data member definition may access the private
members of its class.