What is the difference between enum and enum class?

Oct 3, 2014 at 6:44am
From my understanding, enum declares a bunch of identifiers with an internal integer value starting from 0, 1, 2, 3... (so on). But isn't the enum class basically the same thing? except enum class does not have an internal integer value by default?
Last edited on Oct 3, 2014 at 6:45am
Oct 3, 2014 at 6:48am
The main difference between enum and enum class is that enum class is scoped and strongly typed. As an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
enum Colors {
    RED = 0;
    BLUE = 1;
    GREEN = 2;
};

// You can change between value and name at will, and you don't
// have to specify the scoping. Think of it as adding global constant
// variables.
Colors c = 1; // c = BLUE
c = GREEN;

// OR

enum class Colors {
    Red,
    Blue,
    Green
};

// you have to specify with scoping, you cannot replace with the 
// underlying value or just the name.
Colors c = Colors::Red;
Oct 3, 2014 at 7:05am
Thank you for your response, but why is it that I can't output the value of a member of enum class? I mean I thought every enum variable has an internal value?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

enum {first,second,third,fourth};

enum class greeting :long {whats , up, with, you};

int main ()
{

    
    cout << third; //outputs integer value of 2

    cout << greeting::whats; // compiler says there's an error here


}


Why can't I output any variable from the enum class?
Oct 3, 2014 at 7:44am
Because it is strongly typed. Even though it has an internal type, remember that is an internal type. Either you'll need to cast the value, or overload operator<<:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

enum class Greeting : long {
    whats, up, with, you
};

std::ostream& operator<< (std::ostream& out, const Greeting& g) {
    // could do anything here, I'm demonstrating casting the value
    out << static_cast<long>(g);
    return out;
}

int main() {
    std::cout << Greeting::whats;
    return 0;
}
Topic archived. No new replies allowed.