How to define the size of member vector in constructor of a class?
You can use the member function std::vector::resize
for that
A::A(int size)
{
line.resize(size);
}
The member line
will be default constructed(i.e. std::vector<int> line{}
) before reaching the body of the constructor. And hence writing line(size);
makes no sense, hence
the compiler error.
Much better would be using the member initializer lists, which will help
to construct the vector from the size passed and initialize with 0
's, before reaching the constructor body.
A(int size) : line(size) {}
It uses the following constructor of std::vector
explicit vector( size_type count ); // (since C++11)(until C++14)
explicit vector( size_type count, const Allocator& alloc = Allocator() ); // (since C++14)
You probably want to either use an initializer list:
A::A(int size) : line(size)
{ }
or assign a new value to line
:
A::A(int size)
{
this->line = std::vector(size);
}
These two options will insert size
elements into the vector. So the vector will be filled with default values. If you only want to make sure there is enough space to insert that many elements on a later point in time use reserve to increase capacity of the already constructed vector:
A::A(int size)
{
this->line.reserve(size);
}
Clarification
If you use the first or second option line.size()
and line.capacity()
will be equal size
, because default elements have been inserted into the vector.
With the third option, no default elements will be inserted, so line.size()
will be 0 and line.capacity()
is size
.
The code is wrong because you attempted to re-initialize in the body of your constructor a vector that was already initialized to size 0.
Change your constructor code to use the initializer list
A::A(int size)
: line(size)
{
}