1

I'm creating a new enum:

enum WState {SLEEPING=2, WAITING_FOR_DATA=3, SENDING=4, IDLE=5, ERROR=6};

Then I'm trying to initialize a variable of that enum type to a default state straight after.

WState CurrentState = WState::ERROR;

I can't figure out the correct syntax or maybe I'm missing some vital keywords when searching for an answer. It says:

data member initializer not allowed

enter image description here

5
  • your answer is C++ rule: "data member initializer not allowed" Commented Mar 30, 2013 at 11:44
  • Data member initializer is a C++11 feature. Have you enabled support for that? Commented Mar 30, 2013 at 11:44
  • Oh I misread. So there's an instance variable which you're trying to initialize, I see. Commented Mar 30, 2013 at 11:45
  • Move the initialization to the class constructor. Commented Mar 30, 2013 at 11:47
  • Also, enums don't define their own namespaces : you want Wireless::ERROR instead of WState::ERROR. WState::ERROR in this case will be allowed only because of a Microsoft-specific compiler extension. Commented Mar 30, 2013 at 11:51

1 Answer 1

1

In C++11, what you are doing is allowed. In C++03, however, you have to perform the initialization in the class constructor (possibly in an initialization list, as shown below):

class Wireless
{
public:
    enum WState { /* ... */, ERROR = 6 };
    WState CurrentState;
    Wireless() : CurrentState(WState::ERROR)
    { /* ... */ }

    // ...
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.