Image

C++ - this pointer - Static member

Static member of C++ class

We can define class member static using static keyword. When we declare member of class as static it means no matter how many objects of the class. All static is initialized to zero when the first object is created. If no other initialization is present we can’t put it in the class definition but it can be initialized out of the class.

e.g:
#include<iostream.h>
#include<conio.h>
class Sample{
  static int a;
  public:
	 Sample(int i){
	  a=i;
	 }
	 void show(){
	  cout<<"Static a = "<<a;
	 }

};
int Sample::a;
void main()
{
 Sample s(10);
 clrscr();
 s.show();
 getch();
}
O/P
Static a= 10
WAP to count no of objects created by using static data member
#include<iostream.h>
#include<conio.h>
class Box{
  public:
  static int objectCount;
  double length,breadth,height;
  public:
	 Box(){
	   objectCount++;
	 }
};
int Box::objectCount=0;
void main()
{
 Box b1;
 Box b2;
 Box b3;
 clrscr();
 cout<<"\nTotal objects are : "<<Box::objectCount;
 getch();
}
O/P
Total object are 3