Search code examples
c++arraysconstructorinitializer-list

How do I initialize an array of a non-built-in type in a c++ constructor initializer list?


In C++, I am trying to initialize an array of a non-built-in type in a constructor initializer list. Starting from the code:

class bar {
  int i1,i2;
public:
  bar(i1,i2);
}
class foo {
  bar bar1,bar2;
public:
  foo(int a, int b, int c, int d) : bar1(a,b),bar2(c,d) {};
}

I would like to replace bar1 and bar2 with an array:

bar allbars[2];

How to I change the initializer list to initialize allbars?


Solution

  • Create a proper constructor for bar first.

    class bar {
      int i1,i2;
    public:
      bar(int one, int two)
      : i1(one)
      , i2(two)
      {};
    };
    
    class foo {
      bar allbars[2];
    public:
      foo(int a, int b, int c, int d)
      : allbars{ bar(a,b), bar(c,d) }
      {};
    };