Static Data Members in C++

A data member of a class can be qualified as static (storage-class). The properties of a static member variable are similar to that of a C static variable. Read more about storage classes in C (Click here)

In addition, a static member variable (of a class) has certain special characteristics which are detailed as follows:

  1. It is initialized to zero when the first object of its class is created. No other initialization is permitted
  2. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created
  3. It is visible only within the class, but its lifetime is the entire program

Static variables are normally used to maintain values common to the entire class. For example, a static data member can be used as a counter that records the occurrences of all the objects. Program given below illustrates the use of a static data member.

The output of the above program would be:

In the given program:

  1. Notice the following statement:
    int item::count;
    Note that the type and scope of each static member variable must be defined outside the class definition. This is necessary because the static data members are stored separately rather than as a part of an object. Since they are associated with the class itself rather than with any class objects, they are also known as class variable
  2. The static variable count is initialized to zero when the first objects is created. The count is incremented whenever the data is read into an object. Since the data is read into object three times, the variable count is incremented three times. Because, there is only one copy of count shared by all the three objects, all the three output statements cause the value 3 to be displayed
  3. Static variables are like non-inline member functions in the sense that they are declared in a class definition and defined outside the source file

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *