Good style - return enum or int?

If I have a class that defines an enumeration, should a member function that returns this enumeration return this enumeration or return an int?

For instance:

class Foo { public: enum Stooge { larry, moe, curly}; Stooge WhoToPoke(); // OR: int WhoToPoke(); ??? } 

I declare a method such as returning an enumeration, but I did not know if it was a "better style" or somehow more useful to the client if I declare it as an int.

+4
source share
1 answer

enum provides some type security for the caller ... for example, they cannot pass int as a parameter when Foo::Stooge is expected, or initialize Foo :: Stooge with (uncast) int or enum another type.

A BobTFish comment correctly points out that there is still a lot of nasty code that compiles - more than I remember, as I am not trying to write bad code to keep track of the edges of the compiler check! C ++ 11 improves this for enum class es.

In addition, if you add the function a std::ostream& operator<<(std::ostream&, Stooge) , they can pass a value - the implementation can guarantee a symbolic name (that is, they actually saw "larry", "moe" or "curly" in the stream).

+9
source

Source: https://habr.com/ru/post/1491668/


All Articles