Static Data Member in C++ with example



  • Static Data Members are basically those members which are common to all objects of the class.
  • Static members can be any one of the groups; private, protected, public, but not global data.
  • The access principle of the data member of a class is same for the static data member also.
  • When a static data member is declared and it has only a single copy, it will be shared by all the instance of the class.
  • The static data member must be created and initialized before the main() function.

Note:-Static Variable [Default value = 0]

Example:
#include<iostream.h>
#include<conio.h>
class student
{
int id;
char name[20];
static int count;                               
public:
void get();
void put();
};
               int student :: count;
void student :: get();           
{
cout<<”Enter the Student Info = ”;
cin>>id>>name;
count ++;
}
void student :: put();
{
               cout<<”Student id = ”<<id;
               cout<<” Student name = ”<<name;
               cout<<” count = ”<<count;
}
void main()
{
clrscr();
student st, mt;
               st.get();
               mt.get();
               st.put();
               mt.put();
               getch();
}

No comments:

Post a Comment