Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define static string variable in c++ class

Tags:

c++

string

static

I have 2 questions:

Why is this possible for an int variable:

foo.h:

class foo{

     private:
        const static int a = 42;
};

but for a string variable I need to do it this way?

foo.h:

class foo{

     private:
        static string fooString;
};

foo.cpp:

string foo::fooString = "foo";

And also:

In my particular case foo::fooString should represent a path variable, and I would like that for every object of class foo there were just one instance of foo::string, representing a const value that should never change.

Is there another way to solve this problem?

like image 384
Matteo Avatar asked Feb 25 '26 11:02

Matteo


1 Answers

Why is this possible for an int variable: [..] but for a string variable I need to do it this way?

Just because. Actually you can still make the string const but, yes, you have to define it outside of the class definition. You can only do in-place initialisation of static members when they are const and integral (or "of literal type").

(In C++11 you can even do it for non-static non-const members when they are of literal type.)

I would like that for every object of class foo there were just one instance of foo::string, representing a const value that should never change. Is there another way to solve this problem?

A static const std::string, as you might expect.

// C++03
struct T {
   static const std::string foo;
};

const std::string T::foo = "lol";
like image 56
Lightness Races in Orbit Avatar answered Feb 27 '26 02:02

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!