I have some static const strings as private members of my C++ class. I am aware of the declaration in .h and definition (and initialization) in .cpp practice. In the class constructor I invoke a function that uses these static strings. Surprisingly when in constructor, the strings remain uninitialized (empty strings) which is creating a problem.
Can somebody point out what might be going wrong here? I work with such usage of static const strings all the time but never ran into such situations.
Update: m_data remains empty in utility(). I have a Test class object as a private member of another class.
Here is a kind of code I am using:
// Test.h
class Test
{
public:
Test();
private:
void utility();
static const std::string m_data;
};
// Test.cpp
const std::string Test::m_data = "Data";
Test::Test()
{
utility();
}
void Test::utility()
{
//use m_data here
}
I mase a check of the program anbd it worked fine. In what IDE are you working with ? This on windows right ?
You can use if I am mistaken make the definition if the class itself where you declare the member, the reason cause it is a const static.
I'd use a different approach:
I personally prefer this 'style' and it would remove any issues with having initialised data in the constructor at what is likely to be the minor cost of constructing the string for each instance.
Is this what you need?
Program Output: blah constructor - string initialized to: Hello, Blah!
Is your object of type TEST a global?
If so you are then running into the problem with initialization order.
ie.
The solution is to use a static method to get the string:
Are you defining it as such?
See: Static data members (C++ only)
Based on current code I'd guess you try to create global Test instance, most probably in a different .cpp file. Seems like you are hitting the dreadful static initialization order fiasco. Simply put: the global/static-member variables in a .cpp file will be initialized in the order they are defined. No guarantees are made about global variables in different .cpp files, you cannot rely on var in one file being initialized before or after global variable in another.