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?
It is because all enums in Java are inherited from java. lang. Enum . And extending multiple classes (multiple inheritance) is not allowed in Java.
Inheritance Is Not Allowed for Enums.
C++ does not have a facility to allow one enum type to be extended by inheritance as it does for classes and structures.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With