Reputation: 735
Types.h :
enum MyEnum : int8
{
invalid = -1,
valid = 0,
}
class TestClass
{ ... default stuff ...}
MyOtherHeader.h :
enum MyEnum : int8;
class TestClass;
class MyClass
{
MyEnum Val = -1;
TestClass* MyObj= nullptr;
}
Why can we assign null
to a forward declare Class Pointer, but can't assign a value of the defined underlying type of the enum
to a forwarded declared one?
Shouldn't the compiler be able to "deduce" that properly?
TLDR : The question is : Why do we need a work around to assign a default value to the forward declared enum property?
Upvotes: 0
Views: 219
Reputation: 170065
There is no implicit conversion from an int to an enumeration. As such, you can't copy-initialize (use =
) an enum from an int. So even this
enum MyEnum : int8
{
invalid = -1,
valid = 0,
};
MyEnum e = -1;
Would produce the same error. You can either add a cast, or switch to direct-initialization (which a cast is also a form of, here):
MyEnum e{-1};
The above direct-initializes the variable, though sadly only since C++17. In our particular case you could use it to provide a default member initializer for your member if you can use a C++17 capable compiler. Otherwise, casting is the only way to provide an initializer for an enumeration from an integer.
Upvotes: 1