22 Nov 2019

  • November 22, 2019
  • Amitraj
Static Data Member in C++


-> A data member of a class can be qualified as static .The properties of a static member variable are similar to that of C static variable.

1. It is initialized to zero when the first object of the class is created. no other initialization is permitted (not allowed).

2. Only one copy of that number is created for entire class, and is shared by all the objects of that class, no matter how many objects are created.

3. It is visibles only in the class, but its life time is the entire program.

-> The syntax of the static data members is given as follows −


static data_type data_member_name;

In the above syntax, static keyword is used. The data_type is the C++ data type such as int, float etc. The data_member_name is the name provided to the data member.


// C++ program to demonstrate Static data member.


#include<iostream>
using namespace std;
class  item
{
           static  int count;
        int number;
  public:
          void getdata(int a)
{
         number=a;
             count++;
}
void getcount()
{
      cout<<"count:";
      cout<< count<<"\n";
}
};
int item::count;
 int main()
{
    item  a,b,c;
    a.getcount();
    b.getcount();
    c.getcount();
    
    a.getdata(100);
    b.getdata(200);
    c.getdata(300);

   cout<<"After reading data"<<"\n";
    a.getcount();
    b.getcount();
    c.getcount();
    return 0;
}

OUTPUT:

count: 0
count: 0
count: 0
After reading data
count: 3
count: 3
count: 3

Translate

Popular Posts