Initializing multidimensional arrays in constructor

A

Allan A.

Hi all. Is there any way to initialize an entire array in the constructor.
The code below does not work. Thanks.

class x {
public:
int array[2][2];
x();

};

x::x() {
array = {{1,2},{3,4}};
}
 
I

Ivan Vecerina

: Hi all. Is there any way to initialize an entire array in the
constructor.

No, unfortunately, not in the current version of the C++ standard.
[ it is being proposed to allow this in the next revision of
the standard, but this is still years away. See for example
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1919.pdf ]

: The code below does not work. Thanks.
:
: class x {
: public:
: int array[2][2];
: x();
:
: };
:
: x::x() {
: array = {{1,2},{3,4}};
: }

The actual (proposed) syntax for an initialization would
look like:
x::x()
: array( {{1,2},{3,4}} )
{ }

The example your provided uses assignment, not initialization,
to set the contents of the array. It could become legal as
well if(/once) the above proposal is integrated in the standard.
Equivalent code can (and has) be written today as individual
assignments to each element of the array.


Ivan
 
J

Jay_Nabonne

Hi all. Is there any way to initialize an entire array in the constructor.
The code below does not work. Thanks.

class x {
public:
int array[2][2];
x();

};

x::x() {
array = {{1,2},{3,4}};
}

You could do this:

x::x() {
static int initData[2][2] = {{1,2},{3,4}};
memcpy(array, initData, sizeof(array));
}

- Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top