Static Data Member in C++

A data member of a class can be qualified as static . The properties of a static member variable are similar to that of a static variable. A static member variable has contain special characteristics.

static variable characteristics:

  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 with in the class but its life time is the entire program.
  4. Static variables are normally used to maintain values common to the entire class.
  5. For example a static data member can be used as a counter that records the occurrence of all the objects.

Syntax:

int item :: count; // definition of static data member

Note: 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.

Example:

#include<iostream.h>
class
 item
{
    static int count; //count is static
    int number;
public:
    void getdata(int a)

    {
        number=a;
        count++;
    }
    void getcount(void)
    {
        cout<<”count:”;
        cout<<count<<endl;
    }
};
int item :: count ; //count defined
int main( )
{
   item a,b,c;
   a.get_count( );
   b.get_count( );
   c.get_count( ):
   a.getdata( ):
   b.getdata( );
   c.getdata( );
   cout«"after reading data : "«endl;
   a.get_count( );
   b.gel_count( );
   c.get count( );
   return(0);
}

Output:

static data member variable in c++
count:0
count:0
count:0
After reading data
count: 3
count:3
count:3

The static Variable count is initialized to Zero when the objects created . The count is incremented whenever the data is read into an object. Since the data is read into objects three times the variable count is incremented three times. Because there is only one copy of count shared by all the three object, all the three output statements cause the value 3 to be displayed.

Related posts