Reputation: 3570
Is it possible in the following example to call the "not default constructor" of class A for every element of mVector within the constructor of class B ?
class A {
public:
A (int n) {/*stuff*/}
};
class B {
public:
B (): mVector(10) {} //call A(int n) constructor?
private:
vector<A> mVector;
};
Upvotes: 0
Views: 160
Reputation: 15524
You can use the constructor overload of std::vector
taking an element count and a value which for your use case is equivalent to:
std::vector(size_type count, const T& value);
Use it to initialize the elements with the value type's non default constructor:
std::vector<A> mVector(10, A{0}); // 10 elements copy initialized using 'A{0}'.
Or when initializing in the initialization list:
B() : mVector(10, A{0}) {}
Upvotes: 0
Reputation: 10733
You could do one thing here:-
B() : mVector(10, A(10))
{
}
Or
B() : mVector(10, 10)
{
}
Both are essentially the same thing. However, former one is more efficient.
Upvotes: 0
Reputation: 254461
If you want to set all the elements to the same value, there's a constructor for that
mVector(10, 42) // 10 elements initialised with value 42
If you want to set the elements to different values, use list initialisation
mVector{1,2,3,4,5,6,7,8,9,10} // 10 elements with different values
Strictly speaking, this doesn't do exactly what you describe; it creates a temporary T
, and then uses that to copy-initialise each vector element. The effect should be the same, unless your type has weird copy semantics.
Upvotes: 5