user2738748
user2738748

Reputation: 1116

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.

Upvotes: 1

Views: 8582

Answers (3)

Pait
Pait

Reputation: 757

First: "Testing" for undefined behavior is almost never going to give you the right answer.

This is undefined behavior because you are reading from an uninitialized variable with automatic storage duration. Such a variable has an indeterminate value and must not be read from. Every non-static function scope variable has automatic storage duration.

I think you are confusing the definition of the enum type (which happens inside the class definition) with the declaration of a variable of this type (at function scope). In your example x is a variable with automatic storage duration no matter where the type TYPE has been defined.

Upvotes: 2

HolyBlackCat
HolyBlackCat

Reputation: 96053

If your object don't have any constructors, then it depends on where you create your object. If it's created globally, then all variables are zero-initialized. If not, they are not initialized properly and reading from them results in UB.

You can force zero-initialization of a non-global variable with test x{}; syntax.

Upvotes: 2

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

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”.

Upvotes: 3

Related Questions