0

I already found this really good explanation Initialising enum via constructors but it didn't fit my needs.

So I declare an enum inside a class and want to initialize it inside the class constructor and then call this enum via a switch statement inside a method but I'm not able to implement it. Here is a code:

    class myClass {
        
        myClass();
        
        enum class State;

        void update();

        };
    
    
    //  initialise State() with default value, so state1=0, state2=1
    myClass::myClass() : State() {} 
    
    enum class
        myClass::State
        {
            state1,
            state2
        } enumState;
    
    
    
    
    void myClass::update(){
    
    switch (enumState){
    
    case enumState.state1:
         break;
    case enumState.state2:
         break;

    }
}

But obviously it is not the correct way to implement it.

I get these errors:

error: ‘enum class myClass::State’ is not a non-static data member of ‘myClass’

error: request for member ‘state1’ in ‘enumState’, which is of non-class type ‘myClass::State’

Can someone explain me how to implement such a code and what if I want to initialise State with default parameter ?

Thank you !

1
  • You cannot initialize a type, it is a compile-time construct. You want to do exactly what the suggested answer does - define a member variable and initialize that object in the constructor. Please create a minimal reproducible example, this is a mix of scattered declarations and definitions. E.g. enumState is a global variable. Commented May 12, 2021 at 18:12

1 Answer 1

0

Inside of your class you'll want to include a variable of type State:

class myClass {
    
    myClass();
     
    enum class State;

    // create a class member variable of type State named enumState;
    State enumState;

    void update();
};

Then inside of the constructor you can initialize the new enumState variable instead of the State enum type.

To resolve the second error you're seeing, you'll need to make to the update() method:

void myClass::update(){
    switch (enumState){
    case State::state1:
            break;
    case State::state2:
            break;
    
    }
}

This is due to the way enums values are accessed (using Enum::value rather than enum.value).

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.