holianoify
holianoify

Reputation: 33

How to invoke non-default constructors when using vector resize?

Suppose I create a class

class Foo
{
public:
    Foo(int numofCars, int someValue);

private: 
    vector<Car> carList;
}

Foo::Foo(int numofCars, int someValue)
{
    carList.resize(numofCars);
}

My understanding is that after resize the vector (carList was an empty vector) will become a list of Car objects by calling the default constructor.

Can I specify the constructor of the Car object being called? For example, instead of calling Car(), I want to call Car(int Value)?

Upvotes: 1

Views: 868

Answers (1)

ikh
ikh

Reputation: 10417

Yes you can. (live example)

carList.resize(numofCars, Cars(42));

see more information.


If you're unwilling to make unnecessary copy, there's a bit complex code.

carList.reserve(numofCars);
for (int i = 0; i < numofCars; i++)
    carList.emplace_back(42);

(live example)

It's probably better, but it's not always efficient - if the cost of "1 creation + 10 copying" is less than the cost of "10 creation". It would be case-by-case.

Upvotes: 1

Related Questions