0

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;
};
1
  • Sortof mVector(10, A(10)) will call the copy constructor of A with the object constructed using the non-default constructor. Commented Dec 17, 2014 at 15:40

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

There's no inheritance here, just a member to initialise.
0

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}) {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.