Search code examples
c++enumsundefinedundefined-behavior

Default value of enum declared in class


I have a class whose member is an enum declared inside this class:

#include<iostream>

class test
{
public:
    enum TYPE{MAN, WOMAN};

    TYPE type;
};


int main()
{
    test x;
    if(x.type == test::MAN) std::cout<<"MAN"<<std::endl;
    if(x.type == test::WOMAN) std::cout<<"WOMAN"<<std::endl;
    std::cout<<"ok"<<std::endl;
    return 0;
}

I know that if an enum is declared at namespace scope, it has a default value 0 and when it's declared locally, it doesn't have any default values, which leads to undefined behavior.

My question is: what if I have an enum which belongs to a class? Is it undefined behavior as well?

I tested the above code and x.type is neither MAN nor WOMAN. However, I've done it for only one compiler and one operating system. I'm interested in a more general answer. I haven't found any information regarding this issue anywhere else.

Edit1: Can referring to this indeterminate value cause segmentation fault?

Edit2: I know this is not a well designed class- it's not mine and I'm trying to debug it. So telling me that I can default-initialize object doesn't solve my problem. Please, treat it as a theoretical question.


Solution

  • The default value of the first name in an enum is 0, regardless of the scope of the enum.

    There is no guaranteed default value of an automatic local variable like test x; in main here. It has an indeterminate value. And it's Undefined Behavior to use that value.

    You can ¹default-initialize it like this:

    test x{};
    

    ¹ A subtle point is that at top level this gives a “value-initialization”.