So in my header file for a class Foo I declare a 2D array of ints like so:
int board[][];
I am intentionally leaving out a size because I want to set that in the constructor. board[][] will not change in size once initialized. One of my constructors looks like this:
Foo(int _board[][]);
In this I want to set board[][] to the same size as _board[][] and to also copy the contents. I have tried using this in the .cpp implementation of Foo:
Foo::Foo(int _board[][]){
board[][] = _board[][]; //Does not work as intended
}
However, this does not work as intended. How can I make board[][] be the same size and have the same contents as _board[][] in the constructor?
C++ is different than Java.
int a[][];is not allowed as variable type. Some misleading C++ feature is that first size is allowed to be left empty:Another misleading C++ feature is that this is allowed in initialization of an array (compiler will count the size):
which is equivalent to:
For your very case – use std::vector:
If you can’t use std::vector for whatever reason – then only solution is to use
int**with both sizes:But be aware that you cannot use this way:
because you must provide a dynamic array:
And since that – you have to implement copy constructor, assignment operator and destructor:
So, just use std::vector.