Uniform Initialization in C++


Here we will discuss about the uniform initialization in C++. This is supported from C++11 version. The uniform initialization is a feature that permits the usage of a consistent syntax to initialize variables and objects which are ranging from primitive type to aggregates. In other words, it introduces brace-initialization that applies braces ({}) to enclose initializer values.

Syntax

type var_name{argument_1, argument_2, .... argument_n}

Initialize Dynamically allocated arrays

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   int* pointer = new int[5]{ 10, 20, 30, 40, 50 };
   cout<lt;"The contents of array are: ";
   for (int i = 0; i < 5; i++)
      cout << pointer[i] << " " ;
}

Output

The contents of array are: 10 20 30 40 50

Initialization of an array data member of a class

Example

 Live Demo

#include <iostream>
using namespace std;
class MyClass {
   int arr[3];
   public:
      MyClass(int p, int q, int r) : arr{ p, q, r } {};
      void display(){
         cout <<"The contents are: ";
         for (int c = 0; c < 3; c++)
            cout << *(arr + c) << ", ";
   }
};
int main() {
   MyClass ob(40, 50, 60);
   ob.display();
}

Output

The contents are: 40, 50, 60,

Implicitly initialize objects to return

Example

 Live Demo

#include <iostream>
using namespace std;
class MyClass {
   int p, q;
public:
   MyClass(int i, int j) : p(i), q(j) {
   }
   void display() {
      cout << "(" <<p <<", "<< q << ")";
   }
};
MyClass func(int p, int q) {
   return { p, q };
}
int main() {
   MyClass ob = func(40, 50);
   ob.display();
}

Output

(40, 50)

Implicitly initialize function parameter

Example

 Live Demo

#include <iostream>
using namespace std;
class MyClass {
   int p, q;
public:
   MyClass(int i, int j) : p(i), q(j) {
   }
   void display() {
      cout << "(" <<p <<", "<< q << ")";
   }
};
void func(MyClass p) {
   p.display();
}
int main() {
   func({ 40, 50 });
}

Output

(40, 50)

Updated on: 27-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements