when I want to have a static pointer as a member of a class I need constexpr
for 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.
If a static data member of integral or enumeration type is declared const (and not volatile), it can be initialized with an initializer in which every expression is a constant expression, right inside the class definition:
As you all know, you can use any member even before it is declared/defined in a class. When you define de constexpr value in the class, the compiler does not have the constexpr function available to be used because it is inside the class.
Static members obey the class member access rules (private, protected, public) . Static member functions are not associated with any object. When called, they have no this pointer. Static member functions cannot be virtual, const, volatile, or ref-qualified .
It does not need an out-of-class definition: If a static data member of integral or enumeration type is declared const (and not volatile ), it can be initialized with an initializer in which every expression is a constant expression, right inside the class definition:
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With