How To Make The Static Member Function in C++
A static member function is not a part of object of class . It is instance dependent and can be accessed directly by using the class name and scope resolution operator . If it is declared and defined in a class,the keyword static should be used only in declaration part .
The following program demonstrates the use of static member which accesses static data. The data member count and the function disp() are declared static in the class counter.But the variable count is initialized to 0 outside the class.
#include <iostream.h>
#include <conio.h>
Class counter
{
Private:
static int count;
Public:
counter()
{
++count
}
static void disp();
}
int counter::count=0;
void counter::disp()
{
cout << count << "\n";
}
main ()
{
cout << "Number of object created before =";
counter:: disp(); // calling function disp() belonging to class counter
counter cntl, cnt2, cnt3, cnt4, cnt5;
cout <<"Number of subject created recently = ";
counter::disp();
getche();
}
you should get the following output on running the program.
Number of objects created before =0
Number of object created recently =5
The following program demonstrates the use of static member which accesses static data. The data member count and the function disp() are declared static in the class counter.But the variable count is initialized to 0 outside the class.
#include <iostream.h>
#include <conio.h>
Class counter
{
Private:
static int count;
Public:
counter()
{
++count
}
static void disp();
}
int counter::count=0;
void counter::disp()
{
cout << count << "\n";
}
main ()
{
cout << "Number of object created before =";
counter:: disp(); // calling function disp() belonging to class counter
counter cntl, cnt2, cnt3, cnt4, cnt5;
cout <<"Number of subject created recently = ";
counter::disp();
getche();
}
you should get the following output on running the program.
Number of objects created before =0
Number of object created recently =5
0 comments:
Post a Comment