Question

when I want to have a static pointer as a member of a class I need constexprfor the initialisation with nullptr.

class Application {
    private:
        constexpr static Application* app = nullptr;
}

Can someone explain me why I need to do that? I cannot find the exact reason why it`s necessary that the static variable has to exist at compile time.

Was it helpful?

Solution

That's because you're initialising it inside the class definition. That's only allowed for constant integral and enumeration types (always) and for constexpr data members (since C++11). Normally, you'd initialise it where you define it (outside the class), like this:

Application.h

class Application {
    private:
        static Application* app;
}

Application.cpp

Application* Application::app = nullptr;

Note that you need to provide the out-of-class definition even in the constexpr case, but it must not contain an initialiser then. Still, I believe the second case is what you actually want.

OTHER TIPS

If you don't want it to be constexpr (and it's not an integer) then you need to initialise it outside of the class body:

class Application
{
private:
    static Application* app;
};

Application* Application::app = nullptr;

Typically, you need to initialise a static member variable outside the class declaration, unless it is const. I think this explains it better than I could.

Static variables do not need to "exist at compile time". But if you want to initialize a static variable inside the class, its value needs to be known at compile time.

However, I do not know the reason for this restriction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top