Avatar ·

How to initialize private static class members in a header file?

Hello! I started learning C++ and encountered a problem when working with static class members. I have a simple class that stores the number of created objects: ```cpp // MyClass.h class MyClass { private: static int counter; // declaration of static member public: MyClass() { ++counter; } int getCounter() const { return counter; } }; ``` I'm trying to initialize `counter` directly in the header file, for example like this: ```cpp static int counter = 0; // error! ``` But the compiler gives an error: "non-const static data member must be initialized out of line". If I make the member public and initialize it in a .cpp file, everything works: ```cpp // MyClass.cpp #include "MyClass.h" int MyClass::counter = 0; ``` But it's inconvenient for me to create a