Saturday 2 October 2010

Static Member Functions



Static Member Functions

Static Member Functions work on data that is common to all the objects of a class.
Static Member Functions work on data that is shared by all the objects of a class.
Static Member Functions do not work on the data that belongs to any individual objects.

The following example makes these things clear.

Example:

#include <iostream.h>
class sample
{
private:
static int count;    //declaring static variable
public:
sample()
{
count++;
}

static void showCount()
{
cout<<endl<<”count = “<<count;
}
};

int sample::count=0;   // defining static variable count

void main()
{
sample s1;
sample::showCount();
sample s2;
sample::showCount();
sample s3;
sample::showCount();
}

Explanation of the above program:
 The above program contains a static data member count. It keeps track of how many objects of the class are created. It is incremented every time an object is constructed. showCount() displays the current value of count.

The function showCount() can be accessed in two ways:

One Way:                                  Another way

Sample s1;                                 sample::showCount()  //it is more elegant way
s1.showCount();

since showCount() is declared as static member function, it need not be called with respect to any object, since Static member functions do not work on data that belongs individual objects. But they work on data that is common to all the objects of a class.

No comments:

Post a Comment