error: ISO C++ forbids in-class initialization of non-const static member
According to a similar SO answer there is another approach, in particular suited for your current implementation (header-only library):
// file "Employee.h"
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class Employee {
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;
}
};
#endif //EMPLOYEE_H
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;
}
The initialization of the static member counter
must not be in the header file.
Change the line in the header file to
static int counter;
And add the following line to your employee.cpp:
int Employee::counter = 0;
Reason is that putting such an initialization in the header file would duplicate the initialization code in every place where the header is included.