static class member with private constructor
14:32 12 Oct 2021

Why can a private constructor be used in this case? I can't explain it to myself. In this case, I initialize the class field (the type of which is the same class) from the outside, since it is static.

I use C++ 17 (gcc 11.2).

#include 

using namespace std;

class MainMenu {
public:
    MainMenu(const MainMenu& other) = delete;
    MainMenu& operator=(const MainMenu& other) = delete;
    static MainMenu& GetInstance() { return _instance; }

private:
    static MainMenu _instance;

    MainMenu() { cout << __PRETTY_FUNCTION__ << endl;}
};

// HERE HERE HERE!!
MainMenu MainMenu::_instance = MainMenu(); // Or just MainMenu MainMenu::_instance;

int main() {
    MainMenu::GetInstance();
    return 0;
}

Result:

MainMenu::MainMenu()

Process finished with exit code 0
c++