Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top