Is it possible to change the behavior of default value initialization of a scoped enum in C++ 20 ?
For exemple, in the following code, I’d like that a MyEnum variable to be initialized automaticatly with MyEnum::No when declared with MyEnum myValue{};
using MyEnumRootType = unsigned int;
using MyEnum = enum class EMyEnum: MyEnumRootType {
Yes = 0x1,
No = 0x2
};
int main() {
const MyEnum myValue{}; // <- 0
std::cout << static_cast<MyEnumRootType>(myValue);
}
>Solution :
That’s not possible directly for an enumeration (except if you are willing to change the value of No to 0x0). Enumerations are not class types (even if there is class in enum class), so you can’t affect their behavior like you can with member functions/constructors/destructors/etc of classes.
Instead you’ll have to make a class wrapper around it in which you can defined a default constructor to do whatever you want.