C++: Uses for Static Data Members - dummies

C++: Uses for Static Data Members

By Stephen R. Davis

Static data members have umpteen uses in C++, but here are just a few. First, you can use static members to keep count of the number of objects floating about.

Remember, however, that this count reflects the number of Student objects (including any temporaries) and not necessarily the number of students.

A closely related use for a static member is as a flag to indicate whether a particular action has occurred. For example, a class Radio may need to initialize hardware before sending the first tune command but not before subsequent tunes. A flag indicating that this is the first tune is just the ticket. This includes flagging when an error has occurred.

Another common use is to provide space for the pointer to the first member of a list — the so-called head pointer. Static members can allocate bits of common data that all objects in all functions share (overuse of this common memory is a really bad idea because doing so makes tracking errors difficult).

Notice how the static member function number() can access the static data member noOfStudents. In fact, that’s the only member of the class that it can access — a static member function is not associated with any object. Were you to declare name() to be static, you could refer to Student::name(), which would immediately beg the question, “Which name?”

The following snippet is only one case where a static method can refer directly to a non-static member:

class Student
{
  public:
    static int elementsInName()
    {
        int sizeOfArray = sizeof(name);
        return sizeOfArray/sizeof(char);
    }
  protected:
    char name[MAX_NAME_SIZE];
};

Here the static method elementsInName() refers to name without referencing any object. This was not legal prior to the 2011 standard. It’s allowed now because the sizeof name is the same for all objects. Thus, it doesn’t matter which object you refer to.

You may wonder why sizeof(name) was divided by sizeof(char). The sizeof(name) returns the number of bytes in the array name. But what you want is the number of elements in name, so you have to divide by the size of each element in name.

But isn’t sizeof(char) equal to 1? Well, maybe, but maybe not. Dividing the sizeof the array by the sizeof a single element always works for all array types.