Saturday, 2 October 2010

STATIC DATA MEMBERS



STATIC DATA MEMBERS

If a data member of a class is declared as static, then only one such item is created for the entire class, irrespective of the number of objects created from that class.

A static data member is useful when all objects of the same class must share a common item of information.

Static data members of a class are used to share information among the objects of a class. 
These static members are class variables which are variables of class but don’t belong to each and every object.

It’s visible only within the class, but its life time is the entire program runs.

Syntax:

class <class-name>
{
static data-type variable-name;
};

Important points about Static Data Members:

  1. Static data members are declared by prefixing the data members with keyword static.
  2. A statement declaring a static data member inside a class will obviously not cause any memory to get allocated with it. This is so because a static member is not a member of any object.
  3. We should not forget to write the statement to define static member variable explicitly.
  4. Making static members private prevents any change from non member functions as only member functions can change the values of static data members.
  5. Introducing static data members does not increase the size of objects.
  6. Static data members can be of any type.
  7. These are not part of objects.
  8. Static data members of integral type can be initialized within class itself.

Example:

#include <iostream.h>
class sample
{
private:
static int index;
int count;

public:
sample(int c)   // constructor
{
index++; 
count=c;
count++;
}

void showData()
{
cout<< endl <<”index = ” << index;
cout<< endl<<”count= ‘ << count;
}
};

int sample::index=0;   // Explicit declaration of static variable is mandatory. 

Void main()
{
sample s1(10);
s1.showData();
sample s2(25);
s2.showData();
sample s3(33);
s3.showData();

}

Output:

Index = 1
Count=-11 
Index=2
Count=26
Index=3
Count = 34

Explanation of the above program:

Index is a static integer variable and it is assigned a value zero. Count is a normal integer variable. Please notice that index and count are incremented in the constructor. In the main function three objects are created s1, s2, s3. Each a time an object is created constructor will be called. Since three different objects are created, constructor is called for three times and index is incremented each time by one. It is important to note that index is shared by all the three objects s1, s2, s3 that is why index is equal to 3. But each object has its own copy of count variable.

No comments:

Post a Comment