C++11: Initializer Lists Explained with Simple Example

In C++11 (Introduction to C++11), Initializer lists are a major addition to the C++ language. In this post we are focusing on Initializer lists with some coding examples.

To understand Initializer lists, we need to first understand the constructors. Constructors are special member functions of a class which is used to initialize the object in desired way. Constructors has the same name as that of class. There could be multiple constructors defined in a class which could be selected based on invoking conditions.

In earlier versions of C++, constructors were designed to take arguments by value or by address/reference which means in order to initialize an object with multiple values then multiple versions of constructor needs to be created to set each value separately. This approach was very error-prone and time consuming for classes containing multiple data members.

Initializer lists was introduced in C++11 to overcome above limitations and it can be used to initialize objects with multiple values quite easily. An initializer list is a comma-separated list of values contained in curly braces which can be used to initialize the object.

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

#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() {
    Person p1{"John Wick", 35};
    p1.printInfo();

    std::vector<int> v{100, 200, 300, 400, 500, 600};
    for (auto i : v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

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

    return 0;
}

In the above example, Person class has two members “name (string)” and “age (int)”. The constructor defined in the above example showcases the usage of Initializer lists to instantiate an object.

Also in the above example, initialization of vector is done to showcase usage of initializer lists with STL classes. Please note that initializer lists support is present with almost all the STL classes.

Also in the above example, array initialization using initializer lists are also showcased.

In short Initializer lists can be used with classes, arrays, or any containers to initialize an object with multiple values in a short and precise manner leading to less error-prone code.

Output of above program are as follows:

Name: John Wick, Age: 35
100 200 300 400 500 600
1 2 3 4 5

Leave a Reply

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