'Member initialization syntax in C++ constructors [closed]

Why does the following not compile?

class A {
    public:
        A(int a) : a_{a} {}
    private:
        int a_;
};


Solution 1:[1]

Why does the following not compile?

Because you're most probably compiling the shown code, with Pre-C++11 standard version.

The curly braces around a in your example, is a C++11 feature.

To solve this you can either compile your program with a C++11(or later) version or use parenthesis () as shown below:

Pre-C++11

class A {
    public:
//-------------------v-v--------->note the parenethesis which works in all C++ versions
        A(int a) : a_(a) {}
    private:
        int a_;
};

C++11 & Onwards

class A {
    public:
//-------------------v-v------->works for C++11 and onwards but not with Pre-C++11
        A(int a) : a_{a} {}
    private:
        int a_;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anoop Rana