Thread: Question on Enum

  1. #1
    Registered User
    Join Date
    Mar 2007

    Question on Enum

    Having problems understanding enum in C++.

    There is an implicit conversion from any enum type to int. Suppose this type exists:

    enum MyEnumType { ALPHA, BETA, GAMMA };

    Then the following lines are legal:

    int i = BETA; // give i a value of 1
    int j = 3 + GAMMA; // give j a value of 5
    But what if I have two different enum types? Say
    enum MyEnumType { ALPHA, BETA, GAMMA };
    enum SomeonesEnumType { ALPHA, SATURDAY, MONDAY };
    and these exist in a seperate class called "Enums".

    if i were to type in my main.cpp,
    which enum would it choose?

    I can't seem to find a way to specify which enum I would like to use (e.g. like in Java, I can just type Enums.MyEnumType.ALPHA and Enums.SomeonesEnumType.ALPHA

  2. #2
    Lean Mean Coding Machine KONI's Avatar
    Join Date
    Mar 2007
    Luxembourg, Europe
    I didn't know that C++ allowed to use the constants inside an enumeration type without first defining a variable of that type...but I can answer your last question:

    enum MyEnumType { ALPHA, BETA, GAMMA };
    MyEnumType x;
    int i = x.ALPHA;
    This is how you specify what enumeration type you would like to use, by declaring a variable of that type.

  3. #3
    Registered User
    Join Date
    Mar 2007
    I tried doing it like this:

    Enums::MyEnumType x;
    int i = x.ALPHA;

    but it didn't work

    The error was:

    Program.cpp: 16: error: request for member 'ALPHA' in 'x', which is a non-class type 'Enums::MyEnumType'

    EDIT: Okay, I just realised that I can't have two ALPHA. It will conflict. Whoops.
    Last edited by markcls; 03-26-2007 at 03:07 AM.

  4. #4
    The larch
    Join Date
    May 2006
    My compiler doesn't even let me compile enumerations that have the same identifiers, named or unnamed.

    One solution I can think of is to use namespaces:

    #include <iostream>
    namespace first {
        enum {VALUE = 1};
    namespace second {
        enum {VALUE = 42};
    int main()
        std::cout << first::VALUE << ' ' << second::VALUE << '\n';

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM
  2. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  3. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM
  4. Enum question
    By Bill 101 in forum C Programming
    Replies: 4
    Last Post: 10-31-2002, 12:33 AM
  5. enum question
    By incognito in forum C++ Programming
    Replies: 1
    Last Post: 12-30-2001, 12:04 AM