Much like the Static
Members, there also exist static member functions. Just as static members,
static functions can also be accessed independently of any specific object and
thus its primary use is to pre-initialize static members before creation of
any object.
The following program illustrates how static member functions are declared
and used:
// Static Member Functions
#include <iostream.h>
class myclass
{
// declare a
static int a;
public:
// static function
static void init(int x){a=x;}
int get(){return a;}
};
// define a
int myclass::a;
void main()
{
// static functions may
// be called independently
// using the class name
myclass::init(100);
myclass obj;
cout<<obj.get();
}
In the above example the static members function (init() ) is used to initialize
the static member variable ‘a’ before object creation.
A few points to remember:
Static member functions can only access other static member of the class
or global data.
Static member functions can’t have a non-static overloaded version.
They don’t have a ‘this’ pointer, this is because static
functions can be called irrespective of specific object (using the class
name and the scope resolution operator ‘::’).
With these restrictions they have very limited applications, one of them as
we discussed is to initialize other static members before object creation.
Related Articles: