R_Kapp
R_Kapp

Reputation: 2858

Enum inheriting from primitive type

From questions such as this and this, I was under the impression that inheriting from a primitive type would cause a compiler error. However, the following code compiles and produces expected output on Ideone.

#include <iostream>

enum class Test : unsigned short int
{
    TEST, TEST2, TEST3, TEST4
};

int main() {
    // your code goes here
    Test ans = Test::TEST3;

    if(ans == Test::TEST3)
    {
        std::cout << "Here" << std::endl;
    }

    return 0;
}

Does the fact that the class is also an enum change the answers in the first two Q&A's? Is this well-defined behavior by the standard?

Upvotes: 19

Views: 10942

Answers (3)

TartanLlama
TartanLlama

Reputation: 65600

This does not mean inheritance, this selects the enum's underlying type. The underlying type is the integral type which is used to represent the enumerator values.

You can see the difference in this example:

#include <iostream>

enum class tiny : bool {
    one, two   
};

enum class bigger : long {
    some, lots   
};

int main(int argc, char *argv[])
{
    std::cout << sizeof(tiny::one) << '\n';    //prints 1
    std::cout << sizeof(bigger::some) << '\n'; //prints 8
}

In C++11 you can specify the underlying type of both scoped (i.e. class) and unscoped enums.

Upvotes: 34

Pete Becker
Pete Becker

Reputation: 76245

enum class was added in C++11 to allow you to specify the underlying type for an enumeration. It reuses the syntax for inheritance as an analogy, but it is not inheritance.

Upvotes: 11

Jarod42
Jarod42

Reputation: 217135

It is not inheritance, it is the way to specify underlying type.

Upvotes: 6

Related Questions