Why Do You Need Static Members in C++? - dummies

Why Do You Need Static Members in C++?

By Stephen R. Davis

By default, data members are allocated on a per-object basis. For example, each person has his or her own name. You can also declare a member to be shared by all objects of a class by declaring that member static. The term static applies to both data members and member functions, although the meaning is slightly different. Here’s what you need to know about static data members.

The programmer can make a data member common to all objects of the class by adding the keyword static to the declaration. Such members are called static data members.

Most properties are properties of the object. Using the well-worn (one might say, threadbare) student example, properties such as name, ID number, and courses are specific to the individual student. However, all students share some properties — for example, the number of students currently enrolled, the highest grade of all students, or a pointer to the first student in a linked list.

It’s easy enough to store this type of information in a common, ordinary, garden-variety global variable. For example, you could use a lowly int variable to keep track of the number of Student objects.

The problem with this solution, however, is that global variables are outside the class. It’s like putting the voltage regulator for your microwave outside the enclosure. Sure, you could do it, and it would probably work — the only problem is that you wouldn’t be too happy if your dog got into the wires and you had to peel him off the ceiling.

If a class is going to be held responsible for its own state, objects such as global variables must be brought inside the class, just as the voltage regulator must be inside the microwave lid, away from prying paws. This is the idea behind static members.

You may hear static members referred to as class members; this is because all objects in the class share them. By comparison, normal members are referred to as instance members, or object members, because each object receives its own copy of these members.