Search code examples
c++constructornew-operator

Is it possible to pass different arguments in the constructor during the execution of new?


Let's say I have a class with its constructor:

Class MyClass {
  public:
     MyClass(int arg);
  private:
     int a;
};

and a global array:

int MyArray[]={1,2,3,4,5,6,7,8,9,10}

I want to have a dynamic array of pointers to MyClass but each element of the array must call the constructor with different number. I was trying to do something like that but it did not work out

int main()
{
   int i=0;
   MyClass *MyDynArray = new MyClass[10]{MyArray[i++]};
}

Is it possible to do this in C++ without using vectors? Thanks in advance!!


Solution

  • You can do it the same way as you declared the array with the automatic or static storage duration.

    MyClass *MyDynArray = new MyClass[10]{1,2,3,4,5,6,7,8,9,10};