- 2068 Baisakh · 6 marks
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
countandtotalhave a single copy shared by all objects.showSummary()is static, so it can use only static members and is called withEmployee::showSummary().- Static members must be defined outside the class.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Static data member and member function · Object Oriented Programming, chapter 4 · asked 3×
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6
- Access overridden members from derived class · Object Oriented Programming, chapter 6 · asked 2×
- Static and dynamic data structures; array list · Data Structure and Algorithm, chapter 3
- Functions of data link layer · Computer Networks and Security, chapter 3 · asked 3×
- I/O functions used with data files · Computer Programming, chapter 10 · asked 2×
- Truss joint B: temperature and vertical members long · Theory of Structures I, chapter 3 · asked 2×