Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to initialize vector member variable

Tags:

c++

// 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?

like image 864
q0987 Avatar asked Jul 30 '12 16:07

q0987


People also ask

What is the correct way to initialize vector?

Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.

How do you initialize a member variable in C++?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.


4 Answers

See http://en.cppreference.com/w/cpp/language/default_initialization

Default initialization is performed in three situations:

  1. when a variable with automatic storage duration is declared with no initializer
  2. when an object with dynamic storage duration is created by a new-expression without an initializer
  3. when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.

The effects of default initialization are:

  • If T is a class type, the default constructor is called to provide the initial value for the new object.
  • If T is an array type, every element of the array is default-initialized.
  • Otherwise, nothing is done.

Since std::vector is a class type its default constructor is called. So the manual initialization isn't needed.

like image 140
Zeta Avatar answered Oct 03 '22 03:10

Zeta


It depends. If you want a size 0 vector, then you don't have to do anything. If you wanted, say, a size N vector fill of 42s then use the constructor initializer lists:

ClassName() : m_vecInts(N, 42) {}
like image 29
juanchopanza Avatar answered Oct 03 '22 04:10

juanchopanza


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}
}
like image 21
mrts Avatar answered Oct 03 '22 03:10

mrts


You do not have to initialise it explcitly, it will be created when you create an instance of your class.

like image 43
mathematician1975 Avatar answered Oct 03 '22 03:10

mathematician1975