2

A while ago I wrote code resembling this:

struct Thing
{
    int a,b;
};

struct Junk
{
    double x;
    Thing things[10];
};


Junk myjunk[] =
{
    {   23.4, {  {10,20}, {30,40} } },
    {   45.6, {  {55,66}, {77,88} } }
};

Originally Thing had no constructors - just a flat simple struct to hold a couple integers. myjunk[] is meant to be special hand-written data to feed into something. In real life it has dozens of lines not just two. This code compiled fine.

Then this morning I added constructors to Thing, useful elsewhere in the great scheme of things, for example, to call functions like blarf(Thing(123,456)); and create huge arrays on the heap with 'new'.

struct Thing
{
   int a,b;
   Thing();
   Thing(int _a, int _b);    
};

Now it doesn't compile. I get

Error 1 error C2552: 'Junk::things' : non-aggregates cannot be initialized with initializer list

Yes, class with constructors cannot be made this way. What is the quickest simplest fix to get this compiling?

I know C++11 allows some new ways to initialize variables, but it's not clear in this case what's best. I'm not creating a lone Thing, but an array, and that within another struct. 'Junk' will never have a constructor.

Note that there aren't any virtual methods anywhere, and never will be for Thing and Junk. I'm using Visual Studio 2010, and not sure if it's taking source to be C++11 or older C++.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
DarenW
  • 16,549
  • 7
  • 63
  • 102

3 Answers3

2

Change {10, 20} to Thing(10, 20) and so forth.

If you make the constructors constexpr conditional on language version then once you upgrade to a modern compiler you will be able to have the objects initialized at compile-time again:

#if __cplusplus >= 201103L
constexpr
#endif
Thing() : a(0), b(0) {}

#if __cplusplus >= 201103L
constexpr
#endif
Thing(int a, int b) : a(a), b(b) {}
ecatmur
  • 152,476
  • 27
  • 293
  • 366
1

Your code is valid since C++11, so your compiler must not support that. What you can do is initialize the arrays like this:

Junk myjunk[] =
{
    {   23.4, {  Thing(10,20), Thing(30,40) } },
    {   45.6, {  Thing(55,66), Thing(77,88) } }
};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

You can add constructor for Junk with follows

Junk(double _x, initializer_list<Thing> tl) : x(_x){
        int i = 0;
        for (auto & t : tl) {
            things[i] = t;
            ++i;
            if (i >= 10) {
                break;
            }
        }
    }
imlyc
  • 84
  • 5