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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With