0

How to call specific class constructor within operator new[]?

#include <iostream>

class foo
{
  public:
    foo(){std::cout << "\nfoo::foo()\n";}
    foo(int param){std::cout << "\nfoo::foo(int)\n";}
};

int main()
{
  foo* my_array = new foo[45];
  return 0;
}

foo* my_array = new foo[45]; would call foo() constructor. How to call foo(int) constructor?

1

1 Answer 1

4

There is no way to do this for raw arrays. You can achieve similar result with std::vectors' explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type());:

std::vector<foo> my_vector(45, 10);

will create vector with 45 foo objects, each created via foo(10) constructor call.

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

3 Comments

You can shorten that to std::vector v(45, 10);
Aren't you missing the template parameter <foo>? It's also worth noting, that the constructor gets called only once. The other elements will by copies, so an object that manages ressources has to have a proper copy constructor.
There is a way to do this for arrays, it is just a bit tedious for long arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.