Example:1
C++ program to display static member function
#include <iostream>
#include<conio.h>
using namespace std;
class sample
{
private:
static int a;
public:
void abc();
static void disp();
};
int sample::a=10;
void sample::abc()
{
cout<<"This is normal member function"<<endl;
cout<<"a= "<<a<<endl;
a=a+10;
}
void sample::disp()
{
cout<<"a= " << a<<endl;
}
int main()
{
sample s1;
s1.abc();
s1.disp();//static member function can be called using an object
sample::disp(); // static member functionm call be called using class
return(0);
}
Output:
This is normal member function
a= 10
a= 20
a= 20
Example:2
C++ program to count total objects created in the program. (using static member function)
#include <iostream>
#include<conio.h>
using namespace std;
class sample
{
private:
static int a;
public:
sample();
static void disp();
};
int sample::a;
sample::sample()
{
a=a+1;
}
void sample::disp()
{
cout<<"a= " << a<<endl;
}
int main()
{
/* clrscr(); */
sample::disp();//1
sample e1,e2,e3,e4;
sample::disp();//2
e1.disp(); //static member function can also be called
//using an object
getch();
return(0);
}
Output:
a= 0
a= 4
a= 4




