Initialize static variables in C++ class?

They can’t be initialised inside the class, but they can be initialised outside the class, in a source file:

// inside the class
class Thing {
    static string RE_ANY;
    static string RE_ANY_RELUCTANT;
};

// in the source file
string Thing::RE_ANY = "([^\\n]*)";
string Thing::RE_ANY_RELUCTANT = "([^\\n]*?)";

Update

I’ve just noticed the first line of your question – you don’t want to make those functions static, you want to make them const. Making them static means that they are no longer associated with an object (so they can’t access any non-static members), and making the data static means it will be shared with all objects of this type. This may well not be what you want. Making them const simply means that they can’t modify any members, but can still access them.

Leave a Comment