Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good style - return enum or int? [closed]

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.

like image 937
Zane Beckwith Avatar asked Dec 26 '22 00:12

Zane Beckwith


1 Answers

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 classes.

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

like image 70
Tony Delroy Avatar answered Jan 04 '23 18:01

Tony Delroy