Section 2 - Static Class Methods
1B.2.1 Static Class Methods
This same static concept can be applied to class methods. That is, we can place the static keyword in front of a class method to make it a static class method, in contrast to an instance method for that class. What does the static keyword mean in this case?
Well, in our Dog class the static member population gives us a clue. A candidate for a static method in the Dog class might be a method called getPopulation(). This is a method that would return the population number to the client. It certainly would not need to be dereferenced using a particular dog. Why would we ask fido to give us the population information as opposed to lucy? They'll both give us the same answer, and neither has any claim to being the reporter of this information. So we see we would like to be able to use the class name to dereference the getPopulation() member. And that's just how static methods are used.
class Dog { private: static long population; // private static member long licenseNumber; // private instance member public: static int getPopulation(); }; // initialize static member long Dog::population = 0; // then, much later, with other class method definitions int Dog::getPopulation() { return population; }
Now, from main() or any other client:
int main()
{
Dog fido, lucy, watson;
// any time, we can do this:
cout << "\n Pop. " << Dog::getPopulation() << endl;
}
In static class methods, we are simply putting some functionality of the class into it in the form of a method that can be called without a class object. Often, static class methods take objects of the class as arguments, but not always.
Static class methods are just methods that you think best belong inside your class because they pertain to aspects of that class, or modify the objects' private data that might be passed in as arguments to the methods.
Here are the reasons you would declare a class method static. If any of these is true, you should consider making a method static:
- It operates on static member data
- It is not intuitive to call the method using any particular object of the class
- It takes several objects (or an array of objects) of the class as parameters, and no one object of this list stands out as more important than any other object.