2

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. Commented Nov 8, 2012 at 0:26
  • @DavidDoria - 3rd one down. Non-static data member initializers Unfortunately, it seems VS is actually somewhat slow on adopting all of it. Commented Nov 12, 2012 at 20:03

2 Answers 2

4

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.

4
  • Thanks, that is very odd, can I somehow make VS2010 compile in C++11 as well?
    – Bugster
    Commented Aug 14, 2012 at 15:09
  • @ThePlan Apparently there is some support. But I don't use VS, so I wouldn't know how to enable it. Commented Aug 14, 2012 at 15:15
  • Piggy Question: Does this cause memory allocation prior to instantiation? By this I mean the C++11 standard. Commented Nov 12, 2012 at 20:11
  • 1
    @RobertoWilko allocation of the data members happens whenever a Player object gets instantiated. It would be equivalent to using the constructor initialization list. Commented Nov 12, 2012 at 22:20
4
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;
};

Not the answer you're looking for? Browse other questions tagged or ask your own question.