2
votes

I've recently been told that Windows Visual Studio is one of the best IDEs for C++ development, so I decided to get it, but it's my first time using it and I'm already getting a weird error. The following code:

#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;

class Player {
public:
    string name = "Player";
};

int main() {
    cout << "Works";
    return 0;
}

returns error C2864: 'Player::name' : only static const integral data members can be initialized within a class. What is wrong? This code compiled in Codeblocks IDE. Please explain to me what is wrong I don't understand.

2
@RobertoWilko What is the name of this feature on that list? I don't see anything that says if this is or isn't supported in VS2010. - David Doria
@DavidDoria - 3rd one down. Non-static data member initializers Unfortunately, it seems VS is actually somewhat slow on adopting all of it. - ChiefTwoPencils

2 Answers

4
votes
class Player {
public:
    string name = "Player";
};

This syntax has been introduced in C++11. In previous versions of standard, as C++03, that is supported by MSVC, this should look like this:

class Player {
public:
    Player() : name("Player") {}
    string name;
};
4
votes

In C++03, you cannot initialize the data member at the point of declaration. You can do it in the constructor(s).

class Player {
public:
    Player() : name("Player") {}
    string name;
};

In C++11, your code is fine, so it could be that you were compiling with C++11 support in Codeblocks.