Rhyous

November 15, 2009

How to add an enum or enumeration to a class in C++?

Filed under: Uncategorized — J. Abram barneck @ 11:09 am

How to add an enum or enumeration to a class in C++?

Obviously this is simple, but I keep forgetting one element or other of the syntax (usually the terminating semi-colon) so I thought if I made a post about it, I would never forget again, and if I did, I could look at my post and remember.

There are certain parts to an enum configuration:

  1. The enum keyword.
  2. The name of the enumerator. I name this one Items just as an example but it can be named anything you want almost (of course you can’t use C++ keywords).
  3. The open bracket: {
  4. The names of the items separated by comas:
    item1, item2, item3
    Each item has an integer value starting at 0 and incrementing by one. Optionally, you can change a value, and again, ever value thereafter will be +1. So if you want to start at 1 instead of at 0, you would put this:
    item1 = 1, item2, item3
    If you wanted to count from 1,2,3 and then 7,8,9 you could do this:
    item1 = 1, item2, item3, item7 = 7, item8, item9
    Also you can change every item by having every item by assigning every item.

  5. The closing bracket: }
  6. A statement closing semicolon: ;

    So the code for your Items enumerator look like this:

    enum Items 
    {
        item1 = 1, item2, item3
    };
    

    A basic class is shown here:

    class NewObject
    {
    public:
        // Public members and functions
        NewObject();
        ~NewObject();
    protected:
        // Protected members and functions
    private:
        // Private members and functions
    };
    

    So to add an enum to you need to decide, is it a public, protected, or private enum? I think it is most common to have public enumerations so that is what my example shows.

    class NewObject
    {
    public:
        // Public members and functions
        NewObject();
        ~NewObject();
    
        enum Items 
        {
            item1 = 1, item2, item3
        };
    
    protected:
        // Protected members and functions
    private:
        // Private members and functions
    };
    

    Now you can use the enum on any instantiated class.

    Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: