{ads}

6/recent/ticker-posts

Static keyword




 

The data member can be declared as static so that its come to common all instance of the class. In other words, we can say that a static variable is shared among all instantiated of the class.



Four-step for declaration of static data members

  • The static variable initialized to zero at the time of execution of the first object of class
  • It is shared by all instance of the class
  • A static variable can be declared by static keyword 

static int number;

  • If the declaration of the static member in the private section then it must be declared outside the class before the main function 

int class name::number;

Example Program:

Write a class called test static that declare a normal integer variable called indefinite as to its private member. It uses a public function called disp() which declare a static variable called count and display the content of both indefinite and count variable for various instances of the object.

#include<iostream>
using namespace std;
class teststatic
{
 private:
 int indefinite;
 public:
 void disp(int val)
 {
  static int count;
  indefinite=val;
  count=count+val;
  cout<<"\nstatic:"<<count<<endl;
  cout<<"\nindefinite:"<<indefinite;
 }	
};
int main()
{
teststatic obj1,obj2,obj3;
cout<<"The object one"<<endl;
obj1.disp(1);
cout<<"The object two"<<endl;
obj1.disp(2);
cout<<"The object three"<<endl;
obj1.disp(3);
}

Post a Comment

0 Comments