CSE 202: Computer Science II, Winter 2018
Aggregates
Array types

An array is a contiguous sequence of subobjects, all of which are of the same type. Each subobject of an array is called an "element" of that array and the type of every element is the "element type".

The declaration T a[N]; creates the variable a: an array of N elements of element type T. The expression a[0] accesses the first element, a[1] accesses the second element, and so on until a[N-1] which accesses the last element.

Using the subscript operator to access an element gives you a reference to that element, so an expression like a[0] = x; for some value x of type T is valid.

When an array variable is declared with no initializer, every element is default initialized. For class type elements, this means the default constructor will be invoked for each of them; for non-class type elements, nothing is done.

Aside from default initialization, arrays can also be initialized through aggregate initialization.

Aggregate initialization is the initialization of an aggregate (such as an array) from an initializer list.

Here are examples of array initialization:

int a[5]; // indeterminate values int b[3] = { 3, -10, 21 }; // values 3, -10, and 21 int c[100] = { 4, 1 }; // values 4, 1, and 0 for the rest int d[4] = {}; // 0 for all values

The rules for initializing an array from an initializer list is: each element in the array gets copy-initialized from each corresponding value in the initializer list. If there are not enough values in the initializer list or if the initializer list is empty, then the remaining elements get value initialized.

Arrays cannot be copy initialized or copy assigned. To achieve the same effect, you must assign each element manually.

An array variable can be declared with no size as long as it has an initializer, then the size can be deduced:

int x[] = { 4, 5, 6 }; // x implicitly has 3 elements
Class type aggregates

Aggregate initialization also applies to certain class types whose data members are all public access and there are no user-provided constructors.

For a class like:

struct coordinate { double y, x; };

A variable of that type can be initialized like the following:

coordinate c = { 5.0, 6.0 };

A temporary object can also be created from an aggregate type by casting an initializer list to that type: (coordinate){ 2.0, -5.0 }