I have for example the following code:
#include <iostream>
#include <array>
class Base {
public:
Base() : mA(std::array<int,2>()) {}
Base(std::array<int,2> arr) : mA(arr) {}
Base(/* what to write here ??? */);
private:
std::array<int,2> mA;
};
int main()
{
std::array<int,2> a = {423, 12}; // Works fine
Base b(a); // Works fine
Base c({10, 20}); // This is what I need.
return 0;
}
How should I define constructor to allow initialization with as shown in the 3rd line inside "main" above? In general, I need a configurable (in length in compile / run time) structure that will allow initialization with list of numbers, like {1, 2, 3} or (1, 2, 3) or something similar without need to element-by-element copying. I chose std::array for simplicity, but I'm afraid it might not work with this kind of initialization. What container would your recommend?
Thanks, Kostya
You could add a constructor that takes an
std::initializer_list<int>
and copy the contents into the array:Note: If you wanted to hold a number of elements defined at runtime, then you should use a an
std::vector<int>
This has a constructor frominitializer_list<int>
so the code is simpler:You can initialize it like this:
or