0

I'm trying to create a dynamic 2D array of objects using the new keyword. This was my initial code, which worked ok.

class Foo{
    public:

    static Foo ** make2D(int m, int n) {
        Foo **a = new Foo*[m];
        for (int i = 0; i < m; i++) {
            a[i] = new Foo[n];
        }
        return a;
    }
};


int main() {

    Foo ** x = Foo::make2D(2, 2);
    
    return 0;
}

Then I decided to add a constructor inside the class. It looks like this:

Foo(int a, int b){} 

The rest of the code doesn't change, but now i'm not able to create the 2D array. I'm getting an error on instruction a[i] = new Foo[n];:

No matching function for call to 'Foo::Foo()'

It seems that the new Foo[n]; instructions calls the constructor, expecting two parameters, and receiving none.

What can I do to fix the error? Maybe I should use something like malloc?

user207421
  • 305,947
  • 44
  • 307
  • 483
AlexSp3
  • 2,201
  • 2
  • 7
  • 24
  • 1
    The tl;dr, as is so often the case in C++, is "don't use C-style cruft". Make an `std::vector` and everything will work out. – Silvio Mayolo Oct 05 '21 at 02:01
  • 1
    I suppose you could use placement new in order to handle this situation, as the linked answer suggests. But the ***real*** answer here is: don't even use `new` in the first place. It is rarely needed in modern C++. Use `std::vector`, and it will handle everything correctly. Use `reserve()` to effectively allocate the underlying storage, then `emplace_back` to construct each `Foo` in the "array". Mission accomplished, that was pretty easy, wasn't it? – Sam Varshavchik Oct 05 '21 at 02:03
  • 3
    *I'm trying to create a dynamic 2D array of objects using the new keyword* -- `#include ... std::vector> a(m, std::vector(n));` -- – PaulMcKenzie Oct 05 '21 at 02:06
  • Thank you all for your answers. I guess I should start to use vector; seems to be easier and more flexible. – AlexSp3 Oct 05 '21 at 02:10
  • Well worth the time. [Here's a neat example of it in action.](https://stackoverflow.com/a/2076668/4581301) – user4581301 Oct 05 '21 at 03:32

0 Answers0