Skip to main content
2 of 4
add description of file
mucaho
  • 2.1k
  • 21
  • 36

According to a similar SO answer there is another approach, in particular suited for your current implementation (header-only library):

// Employee.h - add include guards
class Employee { /* fill in rest as before */
public:
    Employee(/*...*/) { /* ... */
        getCounter()++;
    }
    ~Employee(/*...*/) { /* ... */
        getCounter()--;
    }

    static auto getCount() -> std::size_t {
        return getCounter();
    }
private:
    // replace counter static field in class context,
    //    with counter static variable in function context
    static auto getCounter() -> std::size_t& {
        static std::size_t counter = 0;
        return counter;
    }
};

I took the liberty to use std::size for representing the non-negative employee count and trailing return syntax for functions.

Accompanying test (ideone link):

#include "Employee.h"
    
int main() {
    std::cout << "Initial employee count = " << Employee::getCount() << std::endl;
    // printed "count = 0"

    Employee emp1 {};
    std::cout << "Count after an employee created = " << Employee::getCount() << std::endl;
    // printed "count = 1"

    {
        Employee emp2 {};
        std::cout << "Count after another employee created = " << Employee::getCount() << std::endl;
        // printed "count = 2"
    }
    std::cout << "Count after an employee removed = " << Employee::getCount() << std::endl;
    // printed "count = 1"

    return 0;
}
mucaho
  • 2.1k
  • 21
  • 36