6
struct POD { int i, j; };    
class A {
  POD m_pod;
public:
  A() : m_pod({1,2}) {} // error
  A() : m_pod(static_cast<POD>({1,2})) {} // error
  A() : m_pod((POD) {1,2}) {} // ok!
};

I see this in an old production code compiled with g++34, until then I din't know this feature.
Is it a g++ specific feature ? If not then, why is typecasting needed and that's too only C-style cast is allowed ?

Jonas
  • 121,568
  • 97
  • 310
  • 388
iammilind
  • 68,093
  • 33
  • 169
  • 336

2 Answers2

6

Actually the following syntax is not allowed by C++ Standard (both C++03, and C++11):

A() : m_pod((POD) {1,2}) {} // ok!

Since GCC compiles this, it is a GCC extension.

If you compile it with -pedantic option, it gives this warning:

pod.cpp:8:29: warning: ISO C++ forbids compound-literals


In C++11, you can write this:

A() : m_pod{1,2} {}

Demo : http://ideone.com/XaO4y

Or simply this:

class A {
  POD m_pod {1,2}; //in-place initialization
public:
  A() {}
};

Ideone doesn't support this though.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
5

The syntax you're using isn't just for initializer lists, it's for any initialization of class types outside of their declarations. For example:

POD p;
p = (POD) {1, 2};

These are called compound literals; they were added to C in C99. They aren't actually supported in C++; GCC allows them in C++ (and C89) as an extension. C++11 adds the syntax:

p = POD({1, 2});

Or in your case:

A() : m_pod(POD({1,2})) {}
Community
  • 1
  • 1
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • I also didn't know that GCC allows `POD p; p = (POD) {1, 2};` syntax. All answers are good; accepting this for usefule information regarding the extensions. – iammilind Jun 06 '12 at 04:50