Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't specify explicit initializer for arrays

Why does this compile in VS 2013

int main()
{

    int a[3] = { 1, 2, 3 };

    return 0;

}

but this gives the error

class TestClass
{

    int a[3] = { 1, 2, 3 };

};

How do I fix it?

like image 587
abalter Avatar asked Nov 21 '25 06:11

abalter


1 Answers

From Bjarne's C++11 FAQ page:

In C++98, only static const members of integral types can be initialized in-class, and the initializer has to be a constant expression. [...] The basic idea for C++11 is to allow a non-static data member to be initialized where it is declared (in its class).

The problem is, VS2013 doesn't implement all the features of C++11, and this is one of them. So what I suggest you use is std::array (take note of the extra set of braces):

#include <array>

class A
{
public:
    A() : a({ { 1, 2, 3 } }) {} // This is aggregate initialization, see main() for another example

private:
    std::array<int, 3> a; // This could also be std::vector<int> depending on what you need.
};

int main()
{
    std::array<int, 3> std_ar2 { {1,2,3} };
    A a;

    return 0;
}

cppreference link on aggregate initialization

If you're interested you can click on this link to see that what you did does compile when using a compiler that has implemented this feature (in this case g++, I've tried it on clang++ and it works too).

like image 188
Borgleader Avatar answered Nov 22 '25 18:11

Borgleader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!