How to Use Static Members in C++ - dummies

How to Use Static Members in C++

By Stephen R. Davis

In C++, you can declare a member to be shared by all objects of a class by declaring that member static. A static data member in C++ is one that has been declared with the static storage class, as shown here:

class Student
    Student(char *pName = "no name") : name(pName)
    ~Student(){ noOfStudents--; }
    static int noOfStudents;
    string name;
Student s1;
Student s2;

The data member noOfStudents is part of the class Student but is not part of either s1 or s2. That is, for every object of class Student, there is a separate name, but there is only one noOfStudents, which all Students must share.

“Well then,” you ask, “if the space for noOfStudents is not allocated in any of the objects of class Student, where is it allocated?” The answer is, “It isn’t.” You have to specifically allocate space for it, as follows:

int Student::noOfStudents = 0;

This somewhat peculiar-looking syntax allocates space for the static data member and initializes it to 0. (You don’t have to initialize a static member when you declare it; C++ will invoke the default constructor if you don’t.) Static data members must be global — a static variable cannot be local to a function.

The name of the class is required for any member when it appears outside its class boundaries.

This business of allocating space manually is somewhat confusing until you consider that class definitions are designed to go into files that are included by multiple source code modules. C++ has to know in which of those .cpp source files to allocate space for the static variable. This is not a problem with non-static variables because space is allocated in every object created.