C++ Avoid typing out constructor

Viewed 59

I have a struct with e.g. 16 fields and want to later initialize the struct with a initalizer list.

Is there a way to avoid retyping all of them in the constructor (given I want to initialize all of them and in the exact order)? Even if they're all plain old data?

Besides being tedious, it seems to me there is simply some way to do this I don't know about.

struct Foo {
  int  A;
  int  B;
  Bar* C;
  // ...

  Foo (
   int  A,
   int  B,
   Bar* C,
   // ...
  ) :
   A(A),
   B(B),
   C(C),
   // ...
  {} 

}

Foo MyFoo = {
 // ...
}
1 Answers

Since your data members are public, you can in fact do this by reducing the amount of code you have. Simply don't provide a constructor:

struct Foo {
  int  A;
  int  B;
  Bar* C;
  // ...
};

and then you can construct a Foo like this:

Foo foo{1, 2, new Bar{}, /* ... */ };

or

Foo foo = {1, 2, new Bar{}, /* ... */ };
Related