Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 constructor delegation with aggregate initialization

Is it possible to invoke aggregate initialization within my own definition of the default ctor?

GCC complains "error: constructor delegates to itself" with the below code:

struct X {
  int x, y, z, p, q, r;
  X(): x{}, y{}, z{}, p{}, q{}, r{} { }  // cumbersome
//X(): X{} { }  // the idea is nice but doesn't compile
};

I'm using memset(this, 0, sizeof(*this)) in the ctor body at the moment.

like image 234
nodakai Avatar asked Nov 09 '22 14:11

nodakai


1 Answers

One way would be to fool overload resolution in the following way:

struct X {
  int x, y, z, p, q, r;
  X(int) : x{}, y{}, z{}, p{}, q{}, r{} { }
  X() : X(0) { }
};

Another way would be to use in-class default member initialization:

struct X {
  int x = 0, y = 0, z = 0, p = 0, q = 0, r = 0;
};

In your specific example you could also do:

struct X {
  std::array<int, 6> vars{};
};
like image 164
101010 Avatar answered Nov 14 '22 21:11

101010