When I create an array of a user-defined class like this, it will default-construct each element:
S s[5]; // calls default constructor five times, one for each S object
But what if my class is not default-construable? How will I be able to instantiate and later use this array?
For example, my class S
may not be default-construable, but it does have another constructor like this:
S(int, int);
How do I make it call this constructor instead of the default one?
struct S
{
const int m;
S(int p, int k) : m(p) {}
};
S arr[4] = {S(1,1), S(1,2), S(1,3), S(1,4)};
Without copy-ctor, you could still use the following C++11 list-initialization -- as Andy Prowl points out the ctor may not be explicit
for this:
S arr[4] = {{1,1}, {1,2}, {1,3}, {1,4}};
For a more scalable solution, you can use either std::array
or std::vector
:
std::array<S,4> make_array()
{
// create array... and return
}
std::array<S,4> arr = make_array();
Use an std::vector
and fill it up with objects that you decide how should be constructed.
For instance, in C++11 you could use the emplace_back()
member function to write something like this:
#include <vector>
std::vector<S> v;
v.emplace_back(42, 1729);
v.emplace_back(0, 6);
// ...
Or even:
std::vector<S> v = { {42, 1729}, {0, 6} };
If the constructor of S
is not marked as explicit
. If that is the case, you would have to write:
std::vector<S> v = { S{42, 1729}, S{0, 6} }.
Back in C++03, where emplace_back()
and uniform initialization did not exist, you could have done:
#include <vector>
std::vector<S> v;
v.push_back(S(42, 1729));
v.push_back(S(0, 6));
// ...
But your class should be copyable in order for that to compile.
in the past i did some:
S** s = new S*[5];
s[0] = new S(1, 2);
s[1] = new S(1, 2);
just to be able to call the other constructors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With