Describe or Explain Static data member and Static member function .
Static data member:-
A Static member are class member that are declared using static keywords. It is used for recording data common to all objects of a class. A data member variable has certain special characteristics:-
i) It is initialized to zero when the first object of its class is created. No other initialization is permitted.
ii)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 object is created . It is visible only within the class , but its lifetime is the entire program
iii)Static data member is defined by keyword .'static'
Syntax:
Data type class name::static_variable Name;
Ex: int item::count;
Program:-
#include<iostream.h>
#include<conio.h>
class item
{
static int count;
int number;
public :
void getdata(int a)
{
number=a;
count++;
}
void getcount()
{
cout<<"Count is "<<count ;
}
};
int main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<"After reading data";
a.getcount();
b.getcount();
c.getcount();
return0;
}
output:-
count is 0
count is 0
count is 0
After reading data
count is 3
count is 3
count is 3
Static member function:-
Like static member variable, we can also have static member functions. A member function that is declared static has the following properties:
A static function can have access to only other static members (functions or variables) declared in the same class.
A static member function is to be called using the class name (instead of its objects) as follows: class-name :: function-name;
Program:-
#include<iostream.h>
class test
{
public:
int code;
static int count;
void setcode()
{
code=++count;
}
void showcode()
{
cout<<”object number”<<code;
}
static void showcount()
{
cout<<”count”<<count;
}
};
int test::count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
}
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}
Output:-
count 2
count 3
object number 1
object number 2
object number 3.