Alex
Alex

Reputation: 876

Accessing enum members from class

So consider this struct:

struct CType
{
    enum DType
    {
        Int,
        Char
    } Type;

    union Value
    {
        int num;
        char alpha;

        Value() {
            this->num = 0;
            this->alpha = '\0';
        };
        ~Value() {};
    } value;
};

How can I do this?

CType u3;
u3.Type = CType::Int;

Why does the above work?

I would have done it this way:

u3.Type = CType::DType::Int;

Thanks in advance.

Upvotes: 1

Views: 884

Answers (2)

Azeem
Azeem

Reputation: 14677

DType is an Unscoped Enumeration that is visible in its enclosing scope:

Unscoped Enumeration (emphasis mine) - pre-C++11:

Each enumerator becomes a named constant of the enumeration's type (that is, name), visible in the enclosing scope, and can be used whenever constants are required.

You're looking for Scoped Enumeration (available since C++11):

Each enumerator becomes a named constant of the enumeration's type (that is, name), which is contained within the scope of the enumeration, and can be accessed using scope resolution operator. There are no implicit conversions from the values of a scoped enumerator to integral types, although static_cast may be used to obtain the numeric value of the enumerator.

See documentation: https://en.cppreference.com/w/cpp/language/enum

So, the DType as a Scoped Enumeration would be:

enum class DType { Int, Char };

and, Int from it can be accessed like this:

DType::Int

Upvotes: 3

Dragan
Dragan

Reputation: 66

Historically, that is how enum works.

Write "enum class" instead of "enum" and you get increased safety and the access syntax that you want.

Upvotes: 2

Related Questions