Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ declaring static enum vs enum in a class

What's the difference between the static enum and enum definitions when defined inside a class declaration like the one shown below?

class Example
{
     Example();
     ~Example();

     static enum Items{ desk = 0, chair, monitor };
     enum Colors{ red = 0, blue, green };
}

Also, since we are defining types in a class, what do we call them? By analogy if I define a variable in a class, we call it a member variable.

like image 930
user3731622 Avatar asked Feb 24 '15 22:02

user3731622


People also ask

Should enum be inside class?

Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

Does enum need to be static?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

What is static enum in C?

static enum direction {UP,DOWN,RIGHT,LEFT}; This declares an enumerated type with the tag name directions , and also defines a number of enumeration constants and their values. The static storage-class is meaningless here, because you are not defining (allocating storage) for an object.

Are enums static by default?

Enums are implicitly public static final . You can refer to a. DOG because you may access static members through instance references, even when null: static resolution uses the reference type, not the instance.


1 Answers

static cannot be applied to enum declarations, so your code is invalid.

From N3337, §7.1.1/5 [dcl.stc]

The static specifier can be applied only to names of variables and functions and to anonymous unions ...

An enum declaration is none of those.

You can create an instance of the enum and make that static if you want.

class Example
{
     enum Items{ desk = 0, chair, monitor };
     static Items items; // this is legal
};

In this case items is just like any other static data member.


This is an MSVC bug; from the linked bug report it seems the compiler will allow both static and register storage specifiers on enum declarations. The bug has been closed as fixed, so maybe the fix will be available in VS2015.

like image 57
Praetorian Avatar answered Sep 19 '22 12:09

Praetorian