Harry Boy
Harry Boy

Reputation: 4777

Create a static initialise class in c++

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?

Upvotes: 1

Views: 52

Answers (1)

Telokis
Telokis

Reputation: 3389

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.

Upvotes: 6

Related Questions