Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make it call the right constructor?

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?

like image 282
user2030677 Avatar asked May 23 '13 21:05

user2030677


3 Answers

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();
like image 171
dyp Avatar answered Nov 15 '22 13:11

dyp


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.

like image 40
Andy Prowl Avatar answered Nov 15 '22 13:11

Andy Prowl


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

like image 28
Exceptyon Avatar answered Nov 15 '22 12:11

Exceptyon