1

I have a class Y which contains an array of size 100 X objects.

class Y{
    unsigned int x_array[100];
};

I need to initialise this array so that all the elements are zero. Is it this possible to do in Visual Studio and if not what can I do? If I do:

unsigned int x_array[100] = {0}; 

I get a compile error saying data member initialisation is not allowed.

(Intel C++ Compiler v13)

user997112
  • 29,025
  • 43
  • 182
  • 361
  • As far as I know data member initialization is a C++11 feature that uses a similar syntax. If you are not using C++11 features, check if there is a compiler setting to force targeting an older standard maybe? EDIT: this is just a wild guess, I havent done any C++ in ages – LostSalad Oct 11 '13 at 22:03
  • 1
    you could always put `x_array()` in the initializer list of the constructor. (and have been able to since vs2010, i believe). – WhozCraig Oct 11 '13 at 22:03
  • @LostSalad I have a feeling this is one feature of C++11 VS2012 doesn't implement. – user997112 Oct 11 '13 at 22:04
  • @user997112 yeah, but it's pretty arb. I'd expect it to work seeing as you can use a similar array initializer for local variables. See question from 2009: http://stackoverflow.com/questions/629017/how-does-array100-0-set-the-entire-array-to-0 – LostSalad Oct 11 '13 at 22:10

1 Answers1

4

What you are trying to do is available only since C++11, in C++03 the following should do:

class Y{
public:
    Y() : x_array() { }
    unsigned int x_array[100];
};

Also consider using std::vector<unsigned int> instead:

#include <vector>

class Y{
public:
    Y() : x(std::vector<unsigned int>(100, 0)) { }
    std::vector<unsigned int> x;
};
LihO
  • 41,190
  • 11
  • 99
  • 167
  • +1. In case the OP is wondering where the first one comes from, C++11 § 8.5,p5-7 *are* implemented in VS since 2010, though you may have to squelch their "Hey, you're using a new 03x feature, just in case you didn't know that." warning. (The warning number escapes me. sry). Edit: I have no idea if Intel's CC can do this, but judging by [this feature list](http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler) I'd be surprised if they don't. and note, v14 does support non-static initializers, so maybe an upgrade is in order. – WhozCraig Oct 11 '13 at 22:18