fork(5) download
  1. #include <iostream>
  2.  
  3. class Employee { /* fill in rest as before */
  4. public:
  5. Employee(/*...*/) { /* ... */
  6. getCounter()++;
  7. }
  8. ~Employee(/*...*/) { /* ... */
  9. getCounter()--;
  10. }
  11.  
  12. static auto getCount() -> std::size_t {
  13. return getCounter();
  14. }
  15. private:
  16. // replace counter static field in class context,
  17. // with counter static variable in function context
  18. static auto getCounter() -> std::size_t& {
  19. static std::size_t counter = 0;
  20. return counter;
  21. }
  22. };
  23.  
  24. int main() {
  25. std::cout << "Initial employee count = " << Employee::getCount() << std::endl;
  26.  
  27. Employee emp1 {};
  28. std::cout << "Count after an employee created = " << Employee::getCount() << std::endl;
  29.  
  30. {
  31. Employee emp2 {};
  32. std::cout << "Count after another employee created = " << Employee::getCount() << std::endl;
  33. }
  34. std::cout << "Count after an employee removed = " << Employee::getCount() << std::endl;
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
Initial employee count = 0
Count after an employee created = 1
Count after another employee created = 2
Count after an employee removed = 1