[LC++]enum, #define, const, static const, or member const???

Jack Lloyd lloyd at acm.jhu.edu
Tue Apr 2 16:51:29 UTC 2002


On Thu, 28 Mar 2002, Mark Phillips wrote:

> I want to define a certain class type.  Objects of this
> type will have an attribute called "kind", indicating what
> kind of object it is.  There will be a finite collection of
> different kinds of object.
>

> You could do
>
> #define EMPTY 0
> #define CAT 1
> #define DOG 2
>
> Or alternatively you could do
>
> enum kindTy {
>    emptyKind, catKind, dogKind
> };
>
> Or you could do
>
> int const emptyKind = 0;
> int const catKind = 1;
> int const dogKind = 2;

Of these three, I would do enum first, #define next, last is const (or
static const). enum makes the most sense, in my opinion.

> Or you could embed these inside the class definition.  But
> would you access them like:
>
>    if (kind == myClassTy::catKind)
>
> or would you access them like:
>
>    if (kind == myClass.catKind)
>
> also I notice that the "npos" member of the standard string class is
> a "static" const.  Should I be using static???

How about:

if(is_cat(kind))
   ...
else if(is_dog(kind))
   ...

etc, so you don't have to see how the types are implemented in code using
these objects, just the code implementing the object and these functions.
Another level of abstraction, etc, etc.

> So as you can see, there are a miriad of different ways I could do this.
> Can anyone give some guidance about which is best?  Or failing this, the
> advantages and disadvantages of the different methods?

#define doesn't make sense unless you need to do type resolution at compile
time (not needed). static const and enum are about equivalent, but enums
are a little bit cleaner, IMHO.

Using objects and inheritence may be a cleaner way of representing this,
depending on what these objects will eventually be.
-J





More information about the tuxCPProgramming mailing list