8

I'm using Visual Studios 2013 and I keep getting this error yet I don't understand why.

class CLI{
    string commands[2] = {"create", "login"};
public:
    void addCommand(), start(), getCommand(string);
};

The error:

error C2536: 'CLI::CLI::commands': cannot specify explicit initializer for arrays
congusbongus
  • 13,359
  • 7
  • 71
  • 99
Ethan
  • 141
  • 1
  • 2
  • 9
  • 1
    It [should work fine](http://coliru.stacked-crooked.com/a/cb3636698f1c9270). Out of curiosity, does [this one](http://coliru.stacked-crooked.com/a/2e5fc954da32c146) work for you? – chris May 27 '14 at 22:52
  • 2
    I won't ask what this is supposed to be: `void addCommand(), start(), getCommand(string);`, since it isn't related to your question. – WhozCraig May 27 '14 at 22:58
  • 1
    You cannot initialize class members in this way before C++11. You need to do it in a constructor instead. – Tobias Brandt May 27 '14 at 23:00
  • @TobiasBrandt, Sure you can; check my first link (and change 1y to 11 if you don't believe me). – chris May 27 '14 at 23:02
  • 2
    @chris: I said _before_ C++11. – Tobias Brandt May 27 '14 at 23:03
  • @TobiasBrandt. Ah, sorry, read that as "with C++11". I probably skipped a word or something. – chris May 27 '14 at 23:12
  • @chris It probably doesn't matter as VS is notoriously immune to standards. – Tobias Brandt May 27 '14 at 23:15
  • 1
    @TobiasBrandt, It's getting better. They are actually putting in a big effort to get caught up in that regard. I'm guessing VS2015 will be (nearly?) finished with C++14, which is much better than they did for C++11 at least. VS2014 should have most of it, too. – chris May 27 '14 at 23:24
  • @chris Nope, the other method doesn't work; same exact error. – Ethan May 28 '14 at 01:14
  • Interesting. I know uniform initialization is implemented, and so are in-class initializers. Interesting that this isn't. – chris May 28 '14 at 19:43
  • Possible duplicate of [cannot specify explicit initializer for arrays](http://stackoverflow.com/questions/20894398/cannot-specify-explicit-initializer-for-arrays) – waldyrious Jan 02 '16 at 16:36

2 Answers2

15

Visual Studio 2013 is not completely C++11 compliant, so, like Tobias Brandt said, you'll need to use a constructor to initialize those members.

Braced init lists are a C++11 feature.

Maple
  • 386
  • 3
  • 7
2

I don't think that in-class member initializers are implemented in VC2013. Instead, initialize the array in a constructor. For example:

class CLI{
    string commands[2];
public:
    CLI() : commands {"create", "login"}
    {}
};
Ricky65
  • 1,657
  • 18
  • 22
  • 3
    I get the same error involving "cannot specify explicit initializer for arrays" when using the constructor – Ethan May 28 '14 at 01:15
  • It's not supported then. You'll have to initialize it in the constructor then. e.g "CLI(){commands[0] = "create";commands[1] = "login";}" – Ricky65 May 28 '14 at 01:25