Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constant string (class member)

I'd like to have a private static constant for a class (in this case a shape-factory).

I'd like to have something of the sort.

class A {    private:       static const string RECTANGLE = "rectangle"; } 

Unfortunately I get all sorts of error from the C++ (g++) compiler, such as:

ISO C++ forbids initialization of member ‘RECTANGLE’

invalid in-class initialization of static data member of non-integral type ‘std::string’

error: making ‘RECTANGLE’ static

This tells me that this sort of member design is not compliant with the standard. How do you have a private literal constant (or perhaps public) without having to use a #define directive (I want to avoid the uglyness of data globality!)

Any help is appreciated.

like image 579
lb. Avatar asked Oct 14 '09 02:10

lb.


People also ask

What is the class of constant string?

Static constant string (class member)

Is string constant in C++?

Because string literals (not including std::string literals) are constants, trying to modify them—for example, str[2] = 'A' —causes a compiler error.

What is static const in C++?

“static const” is basically a combination of static(a storage specifier) and const(a type qualifier). The static determines the lifetime and visibility/accessibility of the variable.


2 Answers

You have to define your static member outside the class definition and provide the initializer there.

First

// In a header file (if it is in a header file in your case) class A {    private:         static const string RECTANGLE; }; 

and then

// In one of the implementation files const string A::RECTANGLE = "rectangle"; 

The syntax you were originally trying to use (initializer inside class definition) is only allowed with integral and enum types.


Starting from C++17 you have another option, which is quite similar to your original declaration: inline variables

// In a header file (if it is in a header file in your case) class A {    private:         inline static const string RECTANGLE = "rectangle"; }; 

No additional definition is needed.

Starting from C++20 instead of const you can declare it constexpr in this variant. Explicit inline would no longer be necessary, since constexpr implies inline.

like image 75
AnT Avatar answered Oct 06 '22 00:10

AnT


In C++11 you can do now:

class A {  private:   static constexpr const char* STRING = "some useful string constant"; }; 
like image 42
abyss.7 Avatar answered Oct 06 '22 00:10

abyss.7