Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing 2D Array In Class Constructor in C++

Tags:

c++

arrays

I define a 2D array in my header file

char map[3][3];

How can I initialize the values in the class constructor like this

 map = {{'x', 'x', 'o'},
       {'o', 'o', 'x'},
       {'x', 'o', 'x'}};
like image 296
Arizona1911 Avatar asked Aug 03 '26 01:08

Arizona1911


1 Answers

Firstly, there is a difference between assignment and initialization. The OP title is about initialization.

Secondly, you have not told us if your 2D array is a class member(static/non static) or a namespace variable.

-Since you mentioned about initializing it in the class constructor, I am assuming that it is a class non static member, because:

$12.6.2/2 - "Unless the mem-initializer-id names the constructor’s class, a non-static data member of the constructor’s class, or a direct or virtual base of that class, the mem-initializer is ill-formed."

Further, as of C++03 the member array cannot be initialized in the constructor initializer list for the case in OP(not sure about C++0x) though.

-If your 2D array is a static member of your class, you should initialize it as you did (with a slight change), but not in the constructor. This should be done in the enclosing namespace scope once and only once in any of the translation units.

char (A::map)[3][3] = {{'x', 'x', 'o'}, 
       {'o', 'o', 'x'}, 
       {'x', 'o', 'x'}};

-Alternatively, if your 2D array is a namespace scope variable, the definition of the array should be taken out of the header file (unless it is also static) as it will cause a redefinition error and be defined and initialized once and only once in any translation unit as

char map[3][3] = {{'x', 'x', 'o'}, 
       {'o', 'o', 'x'}, 
       {'x', 'o', 'x'}}; 
like image 143
Chubsdad Avatar answered Aug 05 '26 13:08

Chubsdad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!