1

I want to have a class that is used for a one off initialization like so:

class Initialise
{
public:
    Initialise()
    {
        m_name = "Jimmy";
    }
    ~Initialise(){}

private:
    std::string m_name;
};

class SomeClass
{
    static Initialise staticStuff; // constructor runs once, single instance
};

int main()
{
    SomeClass testl;

    return 0;
}

When I run the above I find that the constructor of the 'Initialise' class never gets hit in the debugger. Why is this?

2
  • 3
    Initialise() : m_name("Jimmy") { Commented Jul 20, 2015 at 15:58
  • you don't need to declare an instance of SomeClass in order to get the Initialise constructor running Commented Jul 20, 2015 at 16:23

1 Answer 1

6

You didn't define staticStuff, you only declared it.

You have to declare it outside of the class like so :

Initialise  SomeClass::staticStuff;

Here is a live example.


Moreover, like pointed by Borgleader, you should consider using a member initializer list to improve your code.

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

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.