My enum is not a class or namespace

C++EnumsG++C++11

C++ Problem Overview


Hi I have files called MyCode.h and MyCode.cpp

In MyCode.h I have declared

enum MyEnum {Something = 0, SomethingElse = 1};

class MyClass {

MyEnum enumInstance;
void Foo();

}; 

Then in MyCode.cpp:

#include "MyCode.h"

void MyClass::Foo() {
    enumInstance = MyEnum::SomethingElse;
}

but when compiling with g++ I get the error 'MyEnum' is not a class or namespace...

(works fine in MS VS2010 but not linux g++)

Any ideas? Thanks Thomas

C++ Solutions


Solution 1 - C++

The syntax MyEnum::SomethingElse is a Microsoft extension. It happens to be one I like, but it's not Standard C++. enum values are added to the surrounding namespace:

 // header
 enum MyEnum {Something = 0, SomethingElse = 1};

 class MyClass {

 MyEnum enumInstance;
 void Foo();

 }

 // implementation
 #include "MyClass.h"

 void Foo() {
     enumInstance = SomethingElse;
 }

Solution 2 - C++

Scoped enums will not exist until C++0x. For the time being, your code should be

enumInstance = SomethingElse;

You can create an artificial scoped enum by putting the enum's definition inside its own namespace or struct.

Solution 3 - C++

Indeed, C++0x allows that feature. I could enable it successfully in gcc using this command line flag: -std=c++0x

This was with gcc version 4.4.5

Solution 4 - C++

As explain in other answers: syntax MyEnum::SomethingElse is not valid on regular C++98 enums unless your compiler supports them through non-standard extensions.

I personally don't like the declaration enum MyEnum {A, B}; because Type name is not present while using enum values. This can leads to conflict of names in the current name space.

So user should refer to the type name at each enum values. Example to avoid declaring A twice:

enum MyEnum {MyEnum_A, MyEnum_B};
void A(void) {
    MyEnum enumInstance = MyEnum_A;
}

I prefer to use a specific name space or structure. This allow to reference enum values with latest C++ style:

namespace MyEnum {
    enum Value {A,B};
}
void A(void) {
    MyEnum::Value enumInstance = MyEnum::A
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfriartuckView Question on Stackoverflow
Solution 1 - C++Max LybbertView Answer on Stackoverflow
Solution 2 - C++ildjarnView Answer on Stackoverflow
Solution 3 - C++gregn3View Answer on Stackoverflow
Solution 4 - C++JonathanView Answer on Stackoverflow