STATIC MEMBERS OF A CLASS

Both data members and function members of a class can be declared as static. Because the context is a class, there’s a little more to it than the effect of the static keyword outside a class, so let’s look at static data members.

Static Data Members

When you declare a data member of a class to be static, only one instance of the static member is created and this is shared between all objects of the class. Each object gets its own copy of each of the ordinary data members, but only one instance of each static data member exists, regardless of how many class objects have been defined. Figure 7-7 illustrates this.

One use for a static data member is to count how many objects have been created. You could add a static data member to the public section of the CBox class by adding the following statement to the class definition:

    static int objectCount;                // Count of objects in existence

You now have a problem. How do you initialize the static data member?

You can’t initialize the static data member in the class definition — that’s simply a blueprint for an object and initializing values for members are not allowed. You don’t want to initialize it in a constructor, because you want to increment it every time the constructor is called so the count of the number of objects created is accumulated. You can’t initialize it in another member function because ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.