C++11: Uniform Initialization explained with Simple example

In C++11 (Introduction to C++11), “Uniform initialization” syntax is introduced to initialize variables which provides a consistent syntax for all types of data variables initialization. This syntax is defined for all types of objects, arrays etc. In this post we are focusing on Uniform initialization syntax with some coding examples.

Earlier there were multiple ways to initialize variables. For example: basic data type variables could be initialized using assignment operator whereas class objects could be initialized using a constructor.

In C++11, a uniform way of initializing variables is introduced which is called “Uniform Initialization” syntax.

Let’s have a look at the sample code example to understand the usage of uniform initialization.

#include <iostream>
#include <vector>

class Person {
public:
    Person(std::string n, int a) : name{n}, age{a} {}
    void printInfo() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
private:
    std::string name;
    int age;
};


int main() {
    int a{5};
    std::string s{"Welcome to Simpletechtalks.com"};
    std::vector<int> v{1, 2, 3, 4, 5};

    std::cout << a << std::endl;
    std::cout << s << std::endl;

    for (auto i : v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    int arr[]{1, 2, 3, 4, 5};
    for (auto i : arr) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    Person p{"John Wick", 35};
    p.printInfo();
    return 0;
}

In the above example, uniform initialization syntax is used to initialize variables of various data types. It can also be used with user-defined data types as shown in above example.

Output of the above program are as follows:

5
Welcome to Simpletechtalks.com
1 2 3 4 5
1 2 3 4 5
Name: John Wick, Age: 35

Leave a Reply

Your email address will not be published. Required fields are marked *