Write a program to implement static data member in class.

Algorithm to solve the above problem:
1. Create class item with static data member as count.
2. Create a member function to increment the count.
3. Declare the static datamember using scope resolution operator.
4. Display the count value.

Implementation of above program:
#include<iostream>
using namespace std;
class item
{
static int count;
int num;
public:
void getdata(int a)
{
num=a;
count++;
cout<<"Number"<<num;
cout<<"\n";
}
void showcount()
{
cout<<"Count";
cout<<count<<"\n";
}
};
int item::count;
int main()
{
item a,b,c;
a.showcount();
b.showcount();
c.showcount();
a.getdata(20);
b.getdata(30);
c.getdata(40);
a.showcount();
b.showcount();
c.showcount();
}

The output of the above program is tested on www.jdoodle.com
Output:
Count : 0
Count : 0
Count : 0
Number : 20
Number : 30
Number : 40
Count : 3
Count : 3
Count : 3


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: