meysamimani
meysamimani

Reputation: 335

constant capacity vector in class

I want to make a vector in private part of a class that hold only 10 integers but I get " syntax error 'constant' " while making this vector in the private part of class. I know that I can use a constant array instead of vector but why I can't use vector with constant capacity in a class? also if I make this vector in main() function every thing is fine but in the class I get this error!

class A
{
public:
// constructor 
private:
std::vector<int> tests(10); // here I get error
};

Upvotes: 1

Views: 261

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

Default member initializer (since C++11) doesn't support parentheses initializer, but only brace or equals initializer.

Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list

Note that for std::vector, using brace initializer might lead to effect you don't want. (e.g. std::vector<int>{10} initializes a vector with 1 element with value 10.) You can use equals initializer like

std::vector<int> tests = std::vector<int>(10);

BTW: If the size is fixed, you can use std::array instead.

std::array<int, 10> tests;

Upvotes: 3

selbie
selbie

Reputation: 104514

The initialization of your member variable must be in the constructor list of your class.

class A
{
public:
    A(); // contructor
private:
    std::vector<int> tests;
};

A::A() :
tests(10)
{
   // constructor logic
}

Upvotes: 1

Related Questions