RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Uniform and Convenient Initialization Syntax-3 : Page 3

Change We Need
In June 2008, the C++ standards committee accepted a new proposal for a uniform initialization form for class objects, arrays, aggregates, and so on.

Generally speaking, C++0x allows you to use braces more liberally. For example, you can initialize an object that has a user-declared constructor like this:

class A
int a;
int b;
 A(int i, int j);
// C++0x object initializer
A a ={0,0}; //equivalent to: A a(0,0);
Of course, the traditional parenthesized initializer is still valid in C++0x.

But what about containers? Say goodbye to a long list of push_back() calls. In C++0x, you can initialize standard containers easily and efficiently:

// C++0x container initializer
vector<string> vs={ "ab", "cd", "ef"};

map<string, string> dialawhine =
  { {"Alan Greenspan", "+1 (212) 5555-4321"},
    {"Ben Bernanke", "+1 (212) 555-1234"}};
Under the hood, these container classes use a special constructor type called a sequence constructor (a discussion of which is beyond the scope of this article). Suffice it to say, that from an end-user perspective, these initializations just work.

The most daring change in the new C++0x initialization form is the ability to initialize two categories of arrays that have hitherto proved impregnable to initialization. Yes, I'm talking about member arrays and dynamically allocated arrays of POD types.

Here's how you initialize an array member using the new C++0x initialization syntax:

class C {
  int arr[3];
  C(): arr{1,2,3}{} //C++0x member array initializer

Similarly, you can now initialize a dynamically-allocated array like this:

int* p = new int[3] {1,2,3};//C++0x initializer
It's CD Time
At present, most compilers don't support the new C++0x initialization form. However, it won't take long before vendors start incorporating this feature. In September 2008, the C++ standards committee approved the C++0x Working Paper as an official ISO Committee Draft (CD). You can think of the CD as a feature-complete beta. The CD is now being reviewed by all national bodies involved in the standardization process. A second review phase is planned for next year and that will bring us even closer to a Final International Draft Standard.

Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date