2

I cannot believe that something that sounds so simple can be so hard.

class OutputHandler {
private:
    static std::string const errorPrefixes[] = {"INFO", "WARNING", "ERROR", "CRASH"};
};

How do I do this properly? From various documentations I understand that I cannot initialize Static Member Objects, regardless of them being constant.

2 Answers 2

3

Write the initialization outside the class, together with the definition:

class OutputHandler
{
private:
    static std::string const errorPrefixes[];
};

std::string const OutputHandler::errorPrefixes[] = {"INFO", "WARNING", "ERROR", "CRASH"};

(The definition is of course subject to the one-definition-rule and must only appear in one single translation unit, e.g. OutputHandler.cpp.)

Sign up to request clarification or add additional context in comments.

6 Comments

This is literally the only way to do it? (Like it cannot be done automatically when loading the application without any code outside the class definition? )
@Binero: every object (which is odr-used) must be defined. There's no way around that.
@Binero: Why don't you have an array of const char * instead?
Because error: in-class initialization of static data member 'const char* OutputHandler::errorPrefixes []' of incomplete type Code: static char const* errorPrefixes[] = {"INFO", "WARNING", "ERROR", "CRASH"};
This did it for me. Thanks static constexpr char const * const arr[] = {"INFO", "WARNING", "ERROR", "CRASH"};
|
3

You have to initialize your static members in a source file to satisfy the one-definition-rule:

// in .h
class OutputHandler {
private:
    static std::string const errorPrefixes[]; // declaration
};

// in .cpp
// definition
std::string const OutputHandler::errorPrefixes[] = {"INFO", "WARNING", "ERROR", "CRASH"};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.