Reputation: 335
I want to make a vector first without a size ( vector<int> times
) and I want to define its size later in a constructor of a class ( times(size)
).
I can do it by using the initializer list as you see below
class A (int size): times(size) {};
But my question is that why I can not do it in a constructor out of a class like the code below?
I mean why the code below is wrong?
class A
{
public:
A(int size);
private:
std::vector<int> line;
};
A::A(int size)
{
line(size);// here I got the error
}
line(size)
make an error
Upvotes: 6
Views: 1776
Reputation: 32797
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)
Upvotes: 7
Reputation: 11340
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);
}
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
.
Upvotes: 3
Reputation: 2450
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)
{
}
Upvotes: 2