Answer to Question #324956 in C++ for Sudhanshu

Question #324956

Real life example of static data member in class


1
Expert's answer
2022-04-07T04:04:25-0400

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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS