Fables Alive
Fables Alive

Reputation: 2798

Initializing a vector class member in C++

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?

Upvotes: 8

Views: 13152

Answers (2)

Gaurav
Gaurav

Reputation: 123

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

Upvotes: 8

user4581301
user4581301

Reputation: 33932

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.

Upvotes: 13

Related Questions