static variable or data is similar to c program static variable. Here we will learn how to initialize static data member of c++ class. Followings properties are associated with static data member in c++ language.

  • It initialize to zero if there is no value assign.
  • only one copy of static data member is created for all objects of the same class. such data member created only once and initialize when first object of class is created.
  • It is visible only inside the class while it lives till the program exists.

Note: The static data member is declared inside the class while defined  outside the class. take a look at below program.

#include<iostream>
using namespace std;

class abc {
     private:
         static int a; //declaration
     public:
         abc(){};
         ~abc(){};
         void print();
};
int abc::a = 10; //definition

void abc::print()
{
      cout<<a<<endl;
}
int main()
{
    abc obj; // object of abc
    obj.print();
return 0;
}

Note: outside of class we can access static data member with scope resolution operator :: and assign new value to it.like class name :: data member ( abc::a=12 ).

Try below question:
#include<iostream>
using namespace std;
class abc {
    private:
        static int a; //declaration
    public:
        abc(){
                a=++a;
         };
        ~abc(){

};
        void print();
};
int abc::a = 10; //definition

void abc::print()
{
        cout<<a<<endl;
}
int main()
{
    abc obj_1; // object of abc
    abc obj_2;
    obj_2.print();
return 0;
}
When we run the program we will get output 11. why?


Related Contents to follow