Aggregate Initialization in C++

Aggregate Initialization in C++

An aggregate initialization is a collection of items gathered together. Aggregates of mixed types, such as structs and classes, are covered by this definition. An array is a collection of one kind.


Aggragate C/C++ 98 :

struct Foo   //aggregate type
{
        int i;
	float j;
};


int main() { Foo foo = {1, 3.141}; //foo is aggregate-initialized
return foo.j; // foo.i or foo.j are copy-initialized;
}



Case 1: Zero initialized for aggregate:

In below example, since 1 variable of an aggregate is initialized, hence rest will be initialized with zero.

struct Foo   
{
               int i;
	float j;
};
int main()
{
   Foo foo = {1};
   int arr[100] = {} // similarly all elements of array are zero-initialized.
   return foo.j;   
}


Case 2: Brace elision

The below example is for brace elision, as due to presence of single brace initialization will occurs for single aggregate and other aggregate will be initialized with zero.

struct Foo
{
 	int i;
 	int j;
};

struct Bar
{
	Foo f;
	int k;
};

int main()
{
	Bar b = {1,2};  // Equivalent to Bar b = {{1,2}, 0};
	return b.k;  // It returns 0
	
}