1

I am trying to create an array of objects but I want them to be created using a constructor which takes parameters. This has been my attempt so far.

class myclass {
    int n;
    myclass(int n) : n(n) {}
}

int main() {
    int m = 5;
    int n = 4;

    myclass* arr = new myclass(n)[m];
}

How can this be achieved?

  • This is the actual solution to your problem: https://pastebin.com/xj8vySeD – Sam Mar 07 '18 at 17:04
  • @sam, how is that a solution? – SergeyA Mar 07 '18 at 17:06
  • @SergeyA You cannot initialize arrays of objects using non-default constructors – Sam Mar 07 '18 at 17:07
  • @Sam OP does not ask for multi-dimensional array – pm100 Mar 07 '18 at 17:08
  • 1
    @Sam, so what? It is **not** a solution to OPs problem. – SergeyA Mar 07 '18 at 17:09
  • I disagree with the duplicate, because it is not a real solution. But alas. – SergeyA Mar 07 '18 at 17:11
  • @SergeyA - the dup was perfect – pm100 Mar 07 '18 at 17:17
  • @pm, no, it is not. Do I need to explain why? – SergeyA Mar 07 '18 at 17:23
  • Use `std::vector` instead of a C array, specifically [constructor (2)](http://en.cppreference.com/w/cpp/container/vector/vector). It does exactly what you want here. `std::vector vec(m, n);` – Caleth Mar 07 '18 at 17:26
  • @Sam that is indeed not a solution to my problem. However knowing that it is not possible (at least not in this way) actually helps. I guess I will have to get tackle this in another way. – Just_a_newbie Mar 07 '18 at 20:58
  • @Caleth I am actually trying to avoid `std::vector` here because its elements get initialized when the vector does, thus reducing efficiency. Apart from that, since I need an array of fixed size, there is no point in using `std::vector`. – Just_a_newbie Mar 07 '18 at 21:10
  • If m is constexpr, you can use std::array, otherwise std::vector is *exactly* a dynamic array used correctly. There is no overhead. If you merely want *space for* m instances, but don't have them yet, std::vector is *superior*, as reserve doesn't construct values, it just ensures sufficient storage is allocated. newing a C array default constructs the values. – Caleth Mar 07 '18 at 22:50

0 Answers0