1

I am making a game in C++ and I have a problem with enums. I am defining an enum:

enum class CharacterClass {
    warrior = 0,
    scout = 1,
    mage = 2
};

And I am using it in Player class:

class Player
{
    public:
        Player();
        ~Player();

        CharacterClass PlayerClass;

    private:
};

When I am trying to set the state of enum:

Player player();
player.PlayerClass = CharacterClass::mage;

Compiler finds this error:

request for member 'PlayerClass' in 'player', which is of non-class type 'Player()'
Philip Allgaier
  • 3,505
  • 2
  • 26
  • 53
Bravo555
  • 13
  • 5

2 Answers2

3

That's the most vexing parse: player is understood as a function declaration. So player.PlayerClass triggers this error.

Try:

Player player{};  // prefer uniform brace-initialisation 

This blog entry about variable initialization explains very well the pros and cons of each form.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • It is *not* a most-vexing parse. A [**MVP**](https://en.wikipedia.org/wiki/Most_vexing_parse) declares a function that returns an object and takes an unnamed function-type parameter. – WhozCraig Aug 21 '15 at 18:21
  • Why `Player player{};` and not just `Player player;`..? I wanted to know the difference between the two. – unrealsoul007 Aug 21 '15 at 18:24
  • I typed `Player player;` and it's working, I think this is even better than `Player player{};` – Bravo555 Aug 21 '15 at 18:26
  • @Bravo555 I *strongly* advise you initialize your `PlayerClass` member in your currently-missing [member initialization list](https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list) – WhozCraig Aug 21 '15 at 18:35
  • 1
    @WhozCraig most of the examples to illustrate the MVp are indeed as you say. However, it's about the same ambiguity .Scott Meyers who invented the term himself called this precise situation as MVP (in "*Effective Modern C++*", bottom of page 51) – Christophe Aug 21 '15 at 18:35
  • 2
    @Christophe maybe so, I don't own the book. But the formal standard makes no mention of a simple function decl in 8.2 [dcl.ambig.res] that I can find, which specifically notes the case I cited and wiki mentions. Nor does 6.8 [stmt.ambig] cover the OP's case. He (and everyone else) can call it what they want, but I prefer to call it what it is: an erroneously entered function declaration. – WhozCraig Aug 21 '15 at 18:45
  • @Bravo555 in your specific case, your default constructor gets called in both cases. But if you rely on a trivial default constructor, the {} ensure initialization. I've added a link about this topic in the answer. – Christophe Aug 21 '15 at 18:45
2

Player player() does NOT create a variable of type Player! Instead, it declares a function.

SergeyA
  • 61,605
  • 5
  • 78
  • 137