Static Data Members With Syntax Example and Program

Explain Static data members with Syntax Example and Program

Static data members :-

1.   Only a single copy of the Static data members are shared between Objects of the Class.
2. Static data members are initialized using the data type Class-Name and Scope-Resolution Operator and data member-Name
3.  The Static members are declared using  “ static  “ keyword.
4. The access rule of the data members of a class is same for the static data member also.
5. The Static Data Members should be created and initialized before the main function control block  
     begins.
6.     Syntax :-
•       For variables :-   static  data-type  variable-name ;

#include <iostream.h>
#include<conio.h>
    class sample
    {
     static int a;        // declaration
     public:
        void incr( )
        {    a=a+1;    }
        void putdata ( )
        {    cout <<"a="<<a<<endl;    }
    };
        int sample::a;         //by default initialize with 0
    void main ( )
    {    sample x,y,z;
        y. incr ();
        z.putdata( );
      }

Example:
#include<iostream.h>
#include<conio.h>
int g=10;
class sample
{
    int a;
    public :
    static int b;
        void show()
        {
            b++;
            cout<<"\nb = "<<b;

        }
}s1,s2;
int sample :: b;
class other
{    int c;
     public:void value()
        {   s1.b+=2;
        cout<<"\n--b--="<<s1.b;
        }
} o1,o2;
void main()
{       clrscr();
    s1.show() ;
    o1.value();
    s2.show();
    o1.value();
    getch();
}
output:
b=1;
--b--=3
b=4
--b--=6

Labels: