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?

Ivars
  • 2,375
  • 7
  • 22
  • 31
  • possible duplicate of [Initialize array in constructor without using default constructor or assignment](http://stackoverflow.com/questions/3798276/initialize-array-in-constructor-without-using-default-constructor-or-assignment) – Stefano Sanfilippo Jan 19 '14 at 15:49

1 Answers1

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.

tumdum
  • 1,981
  • 14
  • 19
  • 1
    You can shorten that to `std::vector v(45, 10);` – Borgleader Jan 19 '14 at 15:50
  • 1
    Aren't you missing the template parameter ? 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. – typ1232 Jan 19 '14 at 16:03
  • There *is* a way to do this for arrays, it is just a bit tedious for long arrays. – juanchopanza Jan 19 '14 at 16:05