Q8. Demonstrate the Use of Static Data Member and Static Member Function
Question:
Write a program to demonstrate the use of static data member and static member function.
My Approach
-
Static Data Member:
- Ye ek class-level variable hota hai.
- Har object ka alag copy banne ke bajaye, ye sab objects ke liye common hota hai.
-
Static Member Function:
- Ye sirf static members ko access kar sakta hai.
- Class ke objects create kiye bina bhi call kiya ja sakta hai.
Program Code
File Name: static_member_demo.cpp
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNo;
// Static data member
static int studentCount;
public:
// Constructor
Student(string n, int r) : name(n), rollNo(r) {
studentCount++; // har object ke banne par count increment
}
// Member function
void display() {
cout << "Name: " << name << ", Roll No: " << rollNo << endl;
}
// Static member function
static void showCount() {
cout << "Total Students: " << studentCount << endl;
}
};
// Static data member ko class ke bahar initialize karna padta hai
int Student::studentCount = 0;
// ================= Main Function =================
int main() {
Student s1("Intesab Ansari", 101);
Student s2("Sumaira Khan", 102);
Student s3("Rahul Sharma", 103);
cout << "=== Student Records ===" << endl;
s1.display();
s2.display();
s3.display();
cout << "\n=== Using Static Function ===" << endl;
Student::showCount(); // static function ko bina object ke call kiya
return 0;
}Sample Output
=== Student Records ===
Name: Intesab Ansari, Roll No: 101
Name: Sumaira Khan, Roll No: 102
Name: Rahul Sharma, Roll No: 103
=== Using Static Function ===
Total Students: 3Explanation
studentCountek static data member hai jo total students track kar raha hai.- Har naya
Studentobject banne par constructor usse increment kar deta hai. showCount()ek static function hai jo class ke naam se directly call hota hai.
Real-Life Relevance
- Example:
Agar tumhari MCA class me 60 students hain, aur har ek student ka ek roll number aur name alag hai.- Lekin total strength ek hi value hai (60).
- Ye kaam
static data memberkarta hai.
Conclusion
- Static data member sab objects ke liye common hota hai.
- Static functions bina object create kiye bhi call kiye ja sakte hain.
- Ye dono concept memory efficiency aur common properties track karne ke liye useful hain.
Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live
Last updated on