c++c++11enumsswitch-statementenum-class

initializing enum with a constructor


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 !


Solution

  • 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).