Why doesn't this deduce array size?

Viewed 52

I'm wondering why this doesn't work when in a struct or class but does ordinarily when declared outside of a struct or class.

enum options { OPTION1, OPTION2};

int main()
{
    options opts[] = { OPTION1, OPTION2}; // WORKS


    struct DOGG
    {
        //options opts[] = { OPTION1, OPTION2}; // DOESN'T WORK
        options opts2[2] = { OPTION1, OPTION2}; // WORKS
    };
}

Why in the class can it not deduce the size? This seems strange to me and would like to understand why this happens.

1 Answers

Data members might be initialized in different ways. Suppose we have:

struct DOGG
{
    options opts[] = { OPTION1, OPTION2 };            // default member initializer
    DOGG() {}                                         // default member initializer applied
    DOGG(int) : opts { OPTION1 } {}                   // member initializer list applied, default member initializer ignored
    DOGG(long) : opts { OPTION1, OPTION1, OPTION1} {} // member initializer list applied, default member initializer ignored
};

Then what should the size of opts be? This is invalid since the size of array must be known at complie-time. So the size of array won't be deduced from default member initializer (or member initializer list).

Related