Compile error initializing struct member with enum class

467 views Asked by At

Following program giving compilation error as following

// Example program
#include <iostream>
#include <string>

enum class Animation: int{
  Hide=0,
  Show,
  Flicker
};

struct Icon {
  int id;
  char name[10];
  Animation currentAnim; 
  Animation nextAnim;
  int isActive; 
};

static struct Icon IconList[]= {
    {1, "Offline", Animation::Hide, Animation::Hide, 1},
    {2, "Training", Animation::Hide, Animation::Hide, 1},
    {0, 0, Animation::Hide, Animation::Hide, 1}
};

int main()
{
  std::cout << "Doesn't matter";
}

Compilation

23:1: error: cannot convert 'Animation' to 'char' in initialization 23:1: error: cannot convert 'Animation' to 'char' in initialization

If I change the last member of IconsList[] to this, the compilation error is fixed.

{0, "", Animation::Hide, Animation::Hide, 1}

Can you explain the reason? Why I am getting such a compilation error message for the case?

If I use int instead of enum class, I don't face this compilation error

1

There are 1 answers

3
leslie.yao On BEST ANSWER

The braces around the nested initializer lists may be omitted in aggregate initialization,

The braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.

The member name is a subaggregate containing 10 elements, the 2nd 0 in the initializer is just used to initialize the 1st element of name, then Animation::Hide is tried to use to initialize the 2nd and the 3rd element; but Animation can't convert to char implicitly (as a scoped enumeration).

If I use int instead of enum class, I don't face this compilation error

That's because int could convert to char implicitly. Note that for this case some of the members of Icon might be left uninitialized.

You can add braces for nested initializer if your intent is to use 0 to initialize the member name; as the effect the 1st element of name is initialized as 0, and all the remaining elements are value-initialized (zero-initialized) to 0 too, juse same as initializing it with "".

static struct Icon IconList[]= {
    {1, "Offline", Animation::Hide, Animation::Hide, 1},
    {2, "Training", Animation::Hide, Animation::Hide, 1},
    {0, {0}, Animation::Hide, Animation::Hide, 1}
};