If I have a class that defines an enum, should a member function that returns that enum be declared as returning that enum, or as returning an int?
For example:
class Foo {
public:
enum Stooge { larry, moe, curly};
Stooge WhoToPoke();
// OR: int WhoToPoke(); ???
}
I've been declaring such a method as returning the enum, but didn't know if it was 'better style' or somehow more useable for a client if I declare it as int.
The enum
provides some type safety for the caller... for example, they can not pass an int
as a parameter when an Foo::Stooge
is expected, or initialise a Foo::Stooge with an (uncast) int
or an enum
of another type.
BobTFish's comment correctly points out that there's still lots of nasty code that does compile - more than I remembered as I don't try to write bad code to keep probing the edges of compiler checks! C++11 improves on this for enum class
es.
Further, if you add say a std::ostream& operator<<(std::ostream&, Stooge)
function, then they could stream the value - the implementation could guarantee a symbolic name (i.e. they'd actually see "larry", "moe" or "curly" in the stream).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With