Create a real scenario where static data members are useful. Explain with suitable example.

Answers

This answer is not selected as best answer. This answer may not be sufficient for exam.

Your limit has been exceed. We have implemented this system because, We got difficulty on managing our servers. Please donate some amount to remove this limit.

Quota: 0 / 30

Donate

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.

The syntax of the static data members is given as follows −

static data_type data_member_name;

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(void)
{
    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;
}

The output of above program is

Enter roll number: 1
Enter name: Suresh
Enter marks: 70

Roll Number = 1
Name = Suresh
Marks = 70

Enter roll number: 2
Enter name: Julian
Enter marks: 80

Roll Number = 2
Name = Julian
Marks = 80

Enter roll number: 3
Enter name: Rajesh
Enter marks: 90

Roll Number = 3
Name = Rajesh
Marks = 90

Total objects created = 3
If you found any type of error on the answer then please mention on the comment or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .