Correct way to initialize vector member variable

Viewed 84523
// Method One
class ClassName
{
public:
    ClassName() : m_vecInts() {}

private:
    std::vector<int> m_vecInts;
}

// Method Two
class ClassName
{
public:
    ClassName() {} // do nothing

private:
    std::vector<int> m_vecInts;
}

Question> What is the correct way to initialize the vector member variable of the class? Do we have to initialize it at all?

4 Answers

Since C++11, you can also use list-initialization of a non-static member directly inside the class declaration:

class ClassName
{
public:
    ClassName() {}

private:
    std::vector<int> m_vecInts {1, 2, 3}; // or = {1, 2, 3}
}
Related