Static Member Data and Singleton Objects

Quite often, a class needs to manage data that must be shared among all objects of the class. Every object of the class needs full and immediate access to this classwide data. When one object changes a value, this change must be immediately available to every object in the class. In other languages, such classwide data are often called static. So-called static member variables can't be stored with an object's private structure because objects maintain separate copies of their private data. Using global data is a possibility, but that has its own set of limitations. Under the right conditions, a persistent variable is perfectly suited for this application. In this chapter, we implement a static member variable strategy that uses a persistent variable. The implementation creates a standard location and an interface that fit nicely into the group-of-eight framework. The example implementation also includes a way to save and load static variables along with the private variables. Objects with this kind of load and save capability are often called persistent objects. With the introduction of static variables, we can now define a class using only static variables. Objects of an all static variable class are called singleton objects because all objects of the class share a single copy of their variables.