Question

I have the following class:

class washm_t 
{
public:
    enum door_t { closed = 0, open = 1 };
private:
    door_t door_state ;
public:
    int open() ;
};

The problem with the class is that the open name is defined as both the name of the method inside of the class and the value of the enum type.

The question is: can I somehow modify the code so that both open names work inside of the class or should I pick some other name for the open() method or for the open enum type value?

This is how the open() function looks like:

int washm_t::open()
{
    if(door_state == open)          // ~fails, 'open' interpreted as name of method
                                            //  not as name of enum type value
        return 1 ;
    else
        return door_state = open, 0 ;
}
Was it helpful?

Solution

In C++11 you can use enum class:

enum class door_t { closed = 0, open = 1 };

But then you have to refer to door_t::open instead of simply open. This has the advantages and disadvantages of verboseness. enum class is good in these cases where a name conflict is likely, and it effectively adds a generic prefix to the enumerators of the enumeration.

(Actually, in C++11 you don't need to use the class keyword. Simply referring to door_t::open resolves the conflict with no other change.)

You can arrive at a similar solution in C++03 by putting an enum inside a class (hence the syntax of the C++11 feature)

struct door_state {
    enum door_t { closed = 0, open = 1 };
};

You can make this a nested class, or define it before washm_t and use it as a base class

class washm_t : public door_state {
    int open();
};

Now the the member open() overrides the enumerator, but the enumerator is still available as door_state::open, and closed is still available using the same syntax as before.

OTHER TIPS

How about capitalizing the enums, or giving them a sensible prefix?

enum door_t { CLOSED = 0, OPEN = 1 };

enum door_t { door_closed = 0, door_open = 1 };

You can't have symbols under the same namespace or scope with the same name. Compiler can't differentiate one from the other.

The problem here is with the coding convention. I usually prefer to use caps letters for named constants like enums

enum door_t { CLOSED = 0, OPEN = 1 };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top