wiki:CppNotes

Version 1 (modified by hazen, 6 years ago) (diff)

--

Compile time Initialization of Data Structures

In C we are used to doing things like this:

<pre> struct { int a, b; } map_a2b = { {1, 2}, {2, 4}, {4, 8}}; </pre>

To initialize complex data structures. However if you get clever and try to do it in C++ you get in trouble. A very simple case works:

<pre> class int_pair { public:

int a, b;

}; int_pair map_a2b[] = { {1, 2}, {2, 4}, {4, 8}}; </pre>

However a seemingly trivial change breaks it: <pre> class int_pair { public:

int a, b;

}; int_pair map_a2b[] = { {1, 2}, {2, 4}, {4, 8}}; </pre>

This is because only "aggregate" types may be initialized with lists. Whats an aggregate you ask? According to the C++ standard:

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

The above is no longer an aggregate because it has a non-default constructor (sigh).

You might get clever and try to initialize something more complicated like a map:

<pre> std::map<int,int> a[] = { {1, 2}, {2, 4}, {4, 8}}; </pre>

This wont work either, at least not in the current standard (C++98). C++11, whose features are slowly being rolled out in gcc will support this.