Skip to main content

Program using static members

Short answer

The program uses a static data member count to track number of Employee objects and a static total for salary sum, initialized outside the class. A static member function showSummary() displays these, called with class name. Example: after creating three employees, it shows Employees = 3, Total salary = 70000.

Write a program that uses static member functions and static data member.

The program counts the number of objects created using a static data member and displays the count with a static member function. It also keeps a static total of the salary of all employees.

#include <iostream>
using namespace std;

class Employee
{
    int id;
    float salary;
    static int count;              // number of objects
    static float total;            // total salary of all
public:
    Employee(float s)
    {
        id = ++count;
        salary = s;
        total += s;
    }
    void display()
    {
        cout << "Employee " << id << " salary = " << salary << endl;
    }
    static void showSummary()      // static member function
    {
        cout << "Employees = " << count
             << ", Total salary = " << total << endl;
    }
};

int Employee::count = 0;           // definitions of static members
float Employee::total = 0;

int main()
{
    Employee::showSummary();       // call without an object
    Employee e1(20000), e2(35000), e3(15000);
    e1.display();
    e2.display();
    e3.display();
    Employee::showSummary();
    return 0;
}

Output

Employees = 0, Total salary = 0
Employee 1 salary = 20000
Employee 2 salary = 35000
Employee 3 salary = 15000
Employees = 3, Total salary = 70000

Points

  • count and total have a single copy shared by all objects.
  • showSummary() is static, so it can use only static members and is called with Employee::showSummary().
  • Static members must be defined outside the class.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →