Task 3: Write a program to demonstrate the use of static data members.
#include <iostream>
using namespace std;
class Employee {
private:
int empId;
string name;
static int count; // Static data member declaration
public:
// Constructor
Employee(string n) {
count++; // Increment count each time an object is created
empId = count; // Assign current count as employee ID
name = n;
}
// Member function to display employee details
void display() {
cout << "Employee ID: " << empId << endl;
cout << "Name: " << name << endl;
cout << "---------------------" << endl;
}
// Static member function to access static data member
static void showCount() {
cout << "Total employees: " << count << endl;
}
};
// Definition and initialization of static data member
int Employee::count = 0;
int main() {
// Create employee objects
Employee e1("John Doe");
Employee e2("Jane Smith");
Employee e3("Mike Johnson");
// Display employee details
cout << "Employee Details:" << endl;
e1.display();
e2.display();
e3.display();
// Display total count using static member function
Employee::showCount();
// Create another employee
Employee e4("Sarah Williams");
cout << "\nAfter adding new employee:" << endl;
e4.display();
Employee::showCount();
return 0;
}
Output
Employee Details:
Employee ID: 1
Name: John Doe
---------------------
Employee ID: 2
Name: Jane Smith
---------------------
Employee ID: 3
Name: Mike Johnson
---------------------
Total employees: 3
After adding new employee:
Employee ID: 4
Name: Sarah Williams
---------------------
Total employees: 4
Explanation
1. Static Data Member:
o static int count is declared inside the class but defined and initialized outside
the class with int Employee::count = 0;
o This single copy is shared by all objects of the class
o It maintains a count of total Employee objects created
2. Key Features:
o The constructor increments count each time a new object is created
o Each employee gets a unique ID based on the current count
o The static member count exists even if no objects of the class exist
3. Static Member Function:
o showCount() is a static member function that can access only static data
members
o It's called using the class name with scope resolution Employee::showCount()
o Static functions can be called without creating any object
4. Object Behavior:
o When e1 is created, count becomes 1 and empId is set to 1
o When e2 is created, count becomes 2 and empId is set to 2
o This pattern continues for all objects
5. Memory Efficiency:
o Only one copy of count exists for the entire class
o All objects share this single copy
o This is more memory efficient than having a separate counter in each object
Static data members are particularly useful for:
Maintaining counts of objects
Sharing common data among all objects
Storing class-wide information
Implementing object tracking systems