HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

How can you define a static data member of type const std::string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
datayouhowconstmemberstdcanstaticdefinestring

Problem

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!)

Solution

Since C++17, you can use an inline variable:

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


Prior to C++17, you have to define your static member outside the class definition and provide the initializer there.
// In a header file (if it is in a header file in your case)
class A {
private:
static const string RECTANGLE;
};

// 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.

Code Snippets

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

Context

Stack Overflow Q#1563897, score: 611

Revisions (0)

No revisions yet.