Just one string member shared by all objects

With this, with each new objetct i'm creating an array of four pointers to four literal char strings:

1
2
3
4
class Seasons
{
    const char * const SEASONS[4] = {"Spring","Summer","Fall","Winter"};
};


But i want just a static array of pointers shared by all class objects, like this:

1
2
3
4
class Seasons
{
    static const char * const SEASONS[4] = {"Spring","Summer","Fall","Winter"};
};


But it doesn't compile, here's the error, and i'm using C++11:

'constexpr' needed for in-class initialization of static data member 'const char* const Seasons::SEASONS [4]' of non-integral type [-fpermissive
Last edited on
constexpr static const char * const SEASONS[4] = {"Spring","Summer","Fall","Winter"};
Thank you Repeater, it's compiling.

But now, why this work:

1
2
3
4
Seasons::Seasons()
{
    cout << "ESTACION: " << SEASONS[0] << endl;
}


And this doesn't work:

1
2
3
4
5
Seasons::Seasons()
{
    int INDEX = 0;
    cout << "ESTACION: " << SEASONS[INDEX] << endl;
}

C++14: If a constexpr static data member is odr-used, a definition at namespace scope is still required, but it cannot have an initializer.

C++17: If a static data member is declared constexpr, it is implicitly inline and does not need to be redeclared at namespace scope. This redeclaration without an initializer (formerly required) is still permitted, but is deprecated.

http://en.cppreference.com/w/cpp/language/static


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

struct Seasons {
    
   Seasons();
   private: static constexpr const char * const season_names[4] = { "Spring", "Summer", "Fall", "Winter" };
};

// C++14: this definition is required, but it cannot have an initializer.
// C++17: this definition is permitted, but it is not required (it is deprecated)
// comment out the following line, and with -std=c++14, there would (or at least should) be an error
// (note: the GNU compiler does swalow this without choking, even in strict C++14 mode. 
//        AFAIK, it is non-conforming in this regard.)
constexpr const char * const Seasons::season_names[4]; // this was required before C++17
 
Seasons::Seasons() {
    
    int INDEX = 0;
    
    // the static data member is odr-used in the following line
    std::cout << "ESTACION: " << season_names[INDEX] << '\n' ;
}
 
int main() {
    
    Seasons s ;
}

http://coliru.stacked-crooked.com/a/68dc515e47fd13e8
Topic archived. No new replies allowed.