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

Mark Phillips mark at austrics.com.au
Thu Mar 28 17:13:04 UTC 2002


Hi,

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.

There are a number of different ways I could implement this
idea, but I'm not sure which is best.  One way is to just
use an integer:

class myClassTy {
private:
   int kindVt;
public:
   int kind() const {return kindVt;}
   bool empty() const {return (kindVt==0);}
   bool cat() const {return (kindVt==1);}
   bool dog() const {return (kindVt==2);}
   myClassTy(int kindAg): kindVt(kindAg) {}
};

The problem with this is that here you need to remember that 0 means 
"empty", 1 means "cat" and 2 means "dog" etc.  And if you ever change
the numbering, it could cause all sorts of trouble.

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;

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???

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?

Thanks,

Mark.





More information about the tuxCPProgramming mailing list