Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum inheriting from primitive type

Tags:

c++

c++11

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?

like image 286
R_Kapp Avatar asked Feb 09 '16 14:02

R_Kapp


People also ask

What class does an enum inherit from?

It is because all enums in Java are inherited from java. lang. Enum . And extending multiple classes (multiple inheritance) is not allowed in Java.

Can enums have inheritance?

Inheritance Is Not Allowed for Enums.

Can enum inherit in C++?

C++ does not have a facility to allow one enum type to be extended by inheritance as it does for classes and structures.

Does enum inherit from object?

Enums cannot inherit from other enums. In fact all enums must actually inherit from System. Enum . C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.


1 Answers

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.

like image 76
TartanLlama Avatar answered Oct 01 '22 19:10

TartanLlama