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


Take Charge and Initialize Your Own Data : Page 3

C++ doesn't initialize automatic variables for you, and if you're unfamiliar with the right syntax or aggregate initialization, you can misuse important library functionsor you might be tempted to skip initialization altogether. Avoid creating unnecessary performance overhead, future maintenance problems, and potential bugs by learning how to correctly initialize data on your own.

Step 3: Aggregate Initialization
In plain English, an aggregate is a POD struct, class or union, or an array of POD elements (including fundamental types). To initialize a POD struct, provide one or more initializers enclosed in curly braces. If there are fewer initializers than the number of members, the remaining members are default-initialized:

struct Person { int age; char name[20]; char address[100]; char occupation[50]; }; Person p={25, "Phileas Fogg", "Saville Row, W1 London"};

In this case, the elements of the array occupation are zero-initialized because no explicit initializer was provided for this member. Just as with arrays, you can easily zero initialize all the members of a struct like this:

Person p={0};

You're probably wondering whether this initailization form would compiled if the first member weren't a scalar type, say:

struct Book { char title[200]; //array instead of a scalar type char author[200]; int page_count; };

Yes, it would:

Book b={0};

Remember that aggregate initialization rules are recursive: the initializer 0 is treated as the initializer of the first member of Book, which is an array. As previously noted, when an array's initialization list contains fewer initializers than the number of its elements, the remaining elements are zero-initialized. The literal 0 first initializes the first element of the array title, letting the compiler zero-initialize all the remaining elements. Because the initialization list of b doesn't provide explicit initializers for the rest of its members, these are zero-initialized as well.

Now suppose you want to declare an array of Book objects. The same form of initialization zero-initializes every element of the array:

Book arr[20] ={0};

Remember, it doesn't matter if you change the definition of Book later, say by adding more data members to it, or if you change the size of the array. The ={0}; initializer ensures that every member is properly initialized.

Danny Kalev is a system analyst and software engineer with 15 years of experience, specializing in C++ and object-oriented analysis and design. He was a member of the ANSI C++ standardization committee between 1997-2001. Danny is the author of ANSI/ISO C++ Professional Programmer's Handbook and the C++ Section Leader for DevX He can be reached at dannykk@inter.net.il
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.