how/where to initialize a static private std::list member ?

Recommended Answers

All 2 Replies

Where: in the source file (not in the header file).
How: like this:

// in my_class.h:

#include <list>

class MyClass {
  private:
    static std::list<int> privateList;
};


// in my_class.cpp:

#include "my_class.h"

std::list<int> MyClass::privateList = std::list<int>();

Or with whatever else you want to initialize it with.

"Or with whatever else you want to initialize it with."

Or nothing at all, and let the initializer for the translation unit call the default constructor, as in:

// myclass.cpp
#include "myclass.h"

std::list<int> MyClass::privateList;

.
.
.

mike_2000_17's approach is equally valid (perhaps more so), and will force it to be initialized, even if there is no other access to the object in this translation unit (.cpp file).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.