c++methodsenums

Can a C++ enum class have methods?


I have an enum class with two values, and I want to create a method which receives a value and returns the other one. I also want to maintain type safety(that's why I use enum class instead of enums).

http://www.cplusplus.com/doc/tutorial/other_data_types/ doesn't mention anything about methods However, I was under the impression that any type of class can have methods.


Solution

  • No, they can't.

    I can understand that the enum class part for strongly typed enums in C++11 might seem to imply that your enum has class traits too, but it's not the case. My educated guess is that the choice of the keywords was inspired by the pattern we used before C++11 to get scoped enums:

    class Foo {
    public:
      enum {BAR, BAZ};
    };
    

    However, that's just syntax. Again, enum class is not a class.