Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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";
}


This discloses to me that this kind of part configuration isn't agreeable with the norm. How would you have a private strict consistent (or maybe open) without utilizing a #define order (I need to stay away from the ugliness of information globality!)

Any help is appreciated.
by

3 Answers

espadacoder11
In C++11 you can do now:

class A {
private:
static constexpr const char* STRING = "some useful string constant";
};
pankajshivnani123
In C++ 17 you can use inline variables:

class A {
private:
static inline const std::string my_string = "some useful string constant";
};

Note that this is different from espadacoder11 answer: This one defines an actual std::string object, not a const char*
RoliMishra
This is just extra information, but if you really want the string in a header file, try something like:

class foo
{
public:
static const std::string& RECTANGLE(void)
{
static const std::string str = "rectangle";

return str;
}
};

Login / Signup to Answer the Question.