Uniform initialization is a feature in C++ 11 that allows the usage of a consistent syntax to initialize variables and objects ranging from primitive type to aggregates. In other words, it introduces brace-initialization that uses braces ({}) to enclose initializer values. The syntax is as follows:
type var_name{arg1, arg2, ....arg n}
Following are some of the examples of the different ways of initializing different types:
// uninitialized built-in type
int i;
// initialized built-in type
int j=10;
// initialized built-in type
int k(10);
// Aggregate initialization
int a[]={1, 2, 3, 4}
// default constructor
X x1;
// Parameterized constructor
X x2(1);
// Parameterized constructor with single argument
X x3=3;
// copy-constructor
X x4=x3;
If initialized using brace initialization, the above code can be re-written as:
int i{}; // initialized built-in type, equals to int i{0};
int j{10}; // initialized built-in type
int a[]{1, 2, 3, 4} // Aggregate initialization
X x1{}; // default constructor
X x2{1}; // Parameterized constructor;
X x4{x3}; // copy-constructor
Applications of Uniform Initialization
Initialization of dynamically allocated arrays:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int * pi = new int [5]{ 1, 2, 3, 4, 5 };
for ( int i = 0; i < 5; i++)
cout << *(pi + i) << " " ;
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Initialization of an array data member of a class:
C++
#include <iostream>
using namespace std;
class A
{
int arr[3];
public :
A( int x, int y, int z)
: arr{ x, y, z } {};
void show()
{
for ( int i = 0; i < 3; i++)
cout << *(arr + i) << " " ;
}
};
int main()
{
A a(1, 2, 3);
a.show();
return 0;
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Implicitly initialize objects to return:
C++
#include <iostream>
using namespace std;
class A {
int a;
int b;
public :
A( int x, int y)
: a(x)
, b(y)
{
}
void show() { cout << a << " " << b; }
};
A f( int a, int b)
{
return { a, b };
}
int main()
{
A x = f(1, 2);
x.show();
return 0;
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Implicitly initialize function parameter
C++
#include <iostream>
using namespace std;
class A {
int a;
int b;
public :
A( int x, int y)
: a(x)
, b(y)
{
}
void show() { cout << a << " " << b; }
};
void f(A x) { x.show(); }
int main()
{
f({ 1, 2 });
return 0;
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)