+ 7

How can I assign to each constructor separately when declaring a vector of class objects?

Say I have a class I've named MyClass, with two members, a and b, and a constructor with a member initializer for both. The constructor looks something like this, MyClass::MyClass (int x, int y):a(x), b(y){ } I've made a vector of objects off of the class. vector <MyClass> object1(2, MyClass(15,10)); How can I pass separately to the constructors of object1[0] and object1[1]?

25th Jan 2019, 8:41 AM
Moses Odhiambo
Moses Odhiambo - avatar
1 Odpowiedź
+ 2
You can use an initializer list instead: vector<MyClass> object1 = { MyClass(15,10), MyClass(5, 9) }; You can also use another set of {}'s to make the compiler auto deduce the type: vector<MyClass> object1 = { {15,10}, {5, 9} }; Also the '=' is optional.
25th Jan 2019, 9:14 AM
Dennis
Dennis - avatar