8

I'm trying to set length and initialize a vector member of a class, but it seems it's only possible if initializing line is out of class.

//a vector, out of class set size to 5. initialized each value to Zero
vector<double> vec(5,0.0f);//its ok

class Bird{

public:
    int id;
    //attempt to init is not possible if a vector a class of member
    vector<double> vec_(5, 0.0f);//error: expected a type specifier
}

How can I do this inside the class?

cigien
  • 57,834
  • 11
  • 73
  • 112
Zen Of Kursat
  • 2,672
  • 1
  • 31
  • 47
  • 3
    in C++11, you can have default member values, but not in C++98. The syntax is `vector vec_ = vector(5, 0.0f);` – Franck Nov 10 '16 at 23:46

2 Answers2

13

Use the Member Initializer List

class Bird{

public:
    int id;
    vector<double> vec_;

    Bird(int pId):id(pId), vec_(5, 0.0f)
    {
    }
}

This is also useful for initializing base classes that lack a default constructor and anything else you'd rather have constructed before the body of the constructor executes.

user4581301
  • 33,082
  • 7
  • 33
  • 54
8

As Franck mentioned, the modern c++ way of initializing class member vector is

vector<double> vec_ = vector<double>(5, 0.0f);//vector of size 5, each with value 0.0

Note that for vectors of int, float, double etc (AKA in built types) we do not need to zero initialize. So better way to do this is

vector<double> vec_ = vector<double>(5);//vector of size 5, each with value 0.0

Gaurav
  • 123
  • 2
  • 3