It’s possible to declare a member function as being static. (The keyword static
should appear in the function declaration but not in the function definition if the latter is separate.) This has two important consequences.
First, a static member function doesn’t have to be invoked by an object; in fact, it doesn’t even get a this
pointer to play with. If the static member function is declared in the public section, it can be invoked using the class name and the scope-resolution operator. For instance, you can give the String
class a static member function called HowMany()
with the following prototype/definition in the class declaration:
static int HowMany() { return num_strings; }
It could be invoked like this:
int count = String::HowMany(); // invoking a static member function
The second consequence is that because a static member function is not associated with a particular object, the only data members it can use are the static data members. For example, the HowMany()
static method can access the num_strings
static member, but not str
or len
.
Similarly, a static member function can be used to set a classwide flag that controls how some aspect of the class interface behaves. For example, it can control the formatting used by a method that displays class contents.
18.225.57.126