Real life example of static data member in class
Static data members are class members that are declared using the static keyword. There is only one copy of the static data member in the class, even if there are many class objects. This is because all the objects share the static data member. The static data member is always initialized to zero when the first class object is created.
Example:
#include <iostream>
#include <string.h>
using namespace std;
class Student
{
private:
int rollNo;
char name[10];
int marks;
public:
static int objectCount;
Student()
{
objectCount++;
}
void getdata() {
cout << "Enter roll number: "<<endl;
cin >> rollNo;
cout << "Enter name: "<<endl;
cin >> name;
cout << "Enter marks: "<<endl;
cin >> marks;
}
void putdata()
{
cout<<"Roll Number = "<< rollNo <<endl;
cout<<"Name = "<< name <<endl;
cout<<"Marks = "<< marks <<endl;
cout<<endl;
}
};
int Student::objectCount = 0;
int main()
{
Student s1;
s1.getdata();
s1.putdata();
Student s2;
s2.getdata();
s2.putdata();
Student s3;
s3.getdata();
s3.putdata();
cout << "Total objects created = " << Student::objectCount << endl;
return 0;
}
Comments
Leave a comment