-1

I have a class hi with a non-default constructor taking two arguments. I'm trying to construct an array of his:

class hi {
  public:
    hi(int a, int b){};
};

int main() {
  hi *hello;
  int number_of instance = 5;
  hello = new hi[number_of_instance]; // (1)
}

How to invoke hi::hi(int,int) on the line marked (1)?

1
  • 2
    hello = new hi[5]{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}}; Commented Apr 23, 2018 at 8:18

2 Answers 2

6

How to invoke hi::hi(int,int)?

If hi is actually an aggregate type and/or you're using C++11, you can built it simply with:

hello = new hi[5]{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}};

If hi is not an aggregate, per se you cannot. But with a bit of improvement, we can achieve it.

  1. Declare a private default constructor:

This gives:

class hi {
    hi();
public:
    hi(int a, int b){};
};

Thhe idea is to provide a default constructor for the standard container to find, even though std::is_default_constructible_v<hi> is false. Obviously, any actually attempt to default construct an hi will end in a compilation failure.

  1. Use an std::array or a std::vector instead of a C array:

This gives:

std::vector<hi> his;
  1. Use std::generate_n to construct your objects:

This gives:

his.reserve(number_of_instances);
std::generate_n(std::back_inserter(his), number_of_instances, [](){ return hi{0, 0}; });

Note though, this vector as a vector of non-default constructibe type is uncomplete, you'll be unable to use all of its features.

Demo

Another approach would be to reserve some memory as arrays of unsigned char and construct his instances in it with placement news.

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

9 Comments

Can you explain the reason behind the private default constructor? This however does not answer the original question :/
Reserved memory doesn't count towards the range of the vector. Here begin(his) == end(his)
std::generate_n(std::back_inserter(his), number_of_instances, [](){ return hi{0, 0}; });
@Default look at PasserBy's comment ;)
@Default Jorge comments the last sentence of this answer "Another approach would be to reserve some memory as arrays of unsigned char and..."
|
0

Use a vector

std::vector<hi> hello{{1,2},{1,2},{1,2},{1,2},{1,2}};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.