STATIC MEMBER FUNCTIONS
Like static member variable, we can have static member functions.
A member functions that is declared as static has the following properties
1. A static function can have access to only other static members functions or static variables declared in the same class.
2. A static member function can be called using the class name (instead of its objects) as follows
class-name:: function-name;
|
1. it is initialized to zero when first object of its class is created. No other initialization is permitted.
2. Only single copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
3. it’s visible only within the class, but its lifetime is the entire program
take the example of the static function displaycount() display the number of objects created till that moment. A count of number of
objects created in maintained by the static variable count
in this example showcode() displays the code number of each object
< iostream >
using namespace std;
class test
{
code;
count; // static variable
:
setcode()
{
count=++count;
}
showcode()
{
cout << “object number” << code << “\n”;
}
displaycount() // static member function
{
cout << “count:” << count << “\n”;
}
};
test::count;
main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount(); // accessing static function
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
0;
}
|
count:2
count:3
object number:1
object number:2
object number:3
|
Note : code=++count;
is executed whenever setcode() function is invoked and the current value of count is assigned to code. since object has its own copy of code, the value contained in code represents a unique number of its object
Remember This below code not work
showcount()
{
cout << code; // because code is not static
}
|