Browse DevX
Sign up for e-mail newsletters from DevX


Uniform and Convenient Initialization Syntax-2 : Page 2

Against All PODs
An aggregate is:
  • A POD struct, class, or unions
  • An array of a POD type
The initializer of an aggregate looks like this:

struct Point1{
  int x;
  int y;
Point1 p1 = {1,2}; //aggregate initialization 
However, when you deal with a class that has a constructor, you must use a different initialization form:

class Point2 {
  Point2( int x, int y );
  // ...

Point2 p2(1,0);
This diversity makes the design of generic code difficult because a template that initializes an arbitrary object must know whether the object is an aggregate or a class with a constructor.

Things get messier when you use container objects. Take for example a vector of strings. Today, you have to "initialize" such a container by hand:

vector<string> vs;
vs.push_back( "cd");
Alternatively, you can create an array of strings and use it to initialize the container:

string arr[] = {"ab", "cd", "ef"};  
// initialize the container with an existing array
vector vs( arr, arr+3); 
This is highly inefficient, error-prone, and pretty disgusting.

Initialization Loopholes
Agreed, C++98 initialization is messy. In addition, it has two known loopholes. You have no means of initializing arrays that are data members nor can you initialize dynamically-allocated arrays of POD types. As a workaround, programmers assign a value to each element manually:

//member array 
class C {
  int arr[3];
  C() { arr[0]=1; arr[1]=2; arr[2]=3; }

//dynamically allocated array
int* p = new int[3];
Imagine if you had to "initialize" an array with thousands of elements in this way! This is not to mention the risk of accidentally skipping elements or initializing elements that don't exist. Fortunately, C++0x has a much better solution.

Thanks for your registration, follow us on our social networks to keep up-to-date