Member initialization syntax in C++ constructors

56 Views Asked by At

Why does the following not compile?

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

There are 1 best solutions below

0
On BEST ANSWER

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_;
};