Image

C++ - this pointer - Static Member Function

Static Member Function

By declaring a function member as static you make it independent of any particular object of a class. A static member function can be called even if no object of class exist and the static function are access using only the class name & the scope resolution operator ::.

A static member function can only be access static data members, other static member functions and any other functions from outside the class. Static member function have class scope and they do not have access to this pointer of the class. You could use the static member function to determine whether some object of class have been created or not.

e.g:
#include<iostream.h>
#include<conio.h>
class Box{
  public:
  static int objectCount;
  public:
	 Box(){
	   objectCount++;
	 }
	 static int getCount(){
	  return objectCount;
	 }
};
int Box::objectCount=0;
void main()
{
 clrscr();
 cout<<"\nInitial stage count = "<<Box::getCount();
 Box b1; Box b2; Box b3;
 cout<<"\nTotal objects are   = "<<Box::getCount();
 getch();
}
O/P
Initial stage count =0
Total object are =3