views:

281

answers:

2

does C++ allow to initialize struct using initializer list, {}, if struct has a defined constructor? could not find an answer, but g++ does not seem to allow it.

struct r { int a; };
struct s { int a; s() : a(0) {} };
r = { 1 }; // works
s = { 1 }; // does not work
+11  A: 

No, an object with a constructor is no longer considered a POD (plain old data). Objects must only contain other POD types as non-static members (including basic types). A POD can have static functions and static complex data members.

Note that the upcoming C++ standard will allow you to define initializer lists, which will allow non-POD objects to be initialized with braces.

dauphic
A: 

If by your question you mean to ask, "Can I do this:"

struct MyGizmo
{
  char things_[5];
  MyGizmo() : things_({'a', 'b', 'c', 'd', 'e'}) ();
};

...then the answer is no. C++ doesn't allow this.

John Dibling
No, initializing an array of chars is different from initializing a POD struct that can contain variables of different types. Also, you're doing it the ctor, the OP asked for initialization on an object that has a defined ctor.
Marcus Lindblom
actually, g++ has a heck to do that, not standard: (char[1]){ 0 }
aaa