The static variables are automatically initialized to zero unless it has been initialized
by some other value explicitly.
Static member of a class can be categorized into two types.
1. Static data member
2. Static member function
Static data member
Static data members are data objects that are common to all the objects of a class. They exist only once in all object of this class. The static members are used in information that is commonly accessible. This property of static data members may lead a person to think that static members are basically global variables. This is not true. Static members can be any one of the groups: public, private and protected, but not global data.
Example:
// static data member
# include<iostream.h>
class example
{
private:
static int counter;
public:
void display( );
};
int example::counter =100;
void example::display ( )
{
int i;
for(i =0; i<=10; ++I)
counter = counter+1;
}
cout<<"sum of the counter value ="<<counter
cout<< endl;
}void main( )
{
example obj1;
int i;
for(i = 0; i <=3; ++i)
{
cout<< "count="<<I+1<<endl;
obj.display( );
cout<<endl;
}
output is
count = 1
sum of counter value = 155
count = 2
sum of counter value = 210
count = 3
sum of counter value = 265
Static member function
The key word static is used to precede the member function to make a member function static. The static function is a member function of class and the static member function can manipulate only on static data member of the class. The static member function acts as global for member of its class without affecting the rest of the program. The purpose of static member is to reduce the need for global variables by providing alternatives that are local to a class. A static member function is not part of objects of a class. Static members of a global class have external linkage. A static member function does not have a this pointer so it can access nonstatic members of its class only by .(dot) or ->
The static member function cannot be a virtual function. It cannot be declared with
the keyword const.
Example:
//demonstration of static member function
# include<iostream.h>
class example
{
private:
static int count; //static data member declaration
public:
example( );
static void display( );
};
//static data definition
int example::count = 0;
example::example( )
{
++count;
}
void example::display( )
{
cout<<"counter value ="<< count << endl;
}
void main( )
{
cout<<"before instantiation of the object"<< endl;
example::display ( );
example e1,e2;
cout<<"after instatntiation of the object"<<endl;
example::display ( );
}
output is
before instantion of the object
counter value =0
after instatiation of the object
counter = 2
0 Comments