Characteristics of Static Data Member in C++

A data member of a class can be qualified as static. Static data members can be used as a counter that records the occurrences of all the objects. Static variables are used to maintain values common to the entire class.

Characteristics of Static Data Member:

1. It is initialized to zero when the first object of its class is created.
2. It is visible only within the class, but its lifetime is the entire program.
3. Only one copy of that member is created for the entire class and it is shared by all the objects of that class.

Program:

#include<iostream.h>
#include<conio.h>
using namespace std;
class sample
{
 static int count;
 int number;
public:
 void getdata(int x)
{
 number=x;
 count++;
}
void getcount(void)
{
 cout<<"count:";
 cout<<count<<"\n";
}
};
int sample::count;
int main()
{
 sample p, q, r;
 p.getcount();
 q.getcount();
 r.getcount();
 p.getdata(100);
 q.getdata(200);
 r.getdata(300);
 cout<<"After reading data:"<<"\n";
 p.getcount();
 q.getcount();
 r.getcount();
return 0;
}

Output:

count: 0
count: 0
count: 0
After reading data:
count: 1
count: 1
count: 1

Static Member Functions:

In C++, It can also have static member functions. A member function that is declared by static keyword.

Properties of Static Member Functions:

1. A static member function can have access to only other static member functions or variables declared in the same class.
2. A static member function can be called using the class name given as follows:

class-name::function-name;

Example:

#include<iostream.h>
#include<conio.h>
using namespace std;
class temp
{
  int code;
  static int count;
 public:
  void setcode(void)
{
 code=++count;
}
void showcode(void)
{
 cout<<"Object number:"<<code<<"\n";
}
static void showcount(void)
{
 cout<<"count:"<<count<<"\n";
}
};
int temp::count;
int main()
{
 temp t1, t2;
t1.setcode();
t2.setcode();
temp::showcount();
temp t3;
t3.setcode();
temp::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}

Output:

count: 2
count: 3
Object number: 1
Object number: 2
Object number: 3