Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialisation of static class member. Why constexpr?

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.

like image 891
Matthias Preu Avatar asked Oct 11 '13 13:10

Matthias Preu


People also ask

How to initialize a static data member of an integral class?

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:

Why can't I use de constexpr function inside a class?

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.

What are the rules for static member functions?

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 .

Does a static data member need an out-of-class definition?

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:


2 Answers

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.

like image 124
Angew is no longer proud of SO Avatar answered Sep 27 '22 17:09

Angew is no longer proud of SO


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;
like image 24
Simple Avatar answered Sep 27 '22 18:09

Simple