-1

I need to access a public enum belonging to another class, to simplify, something like this:

class obj
{
public:

    enum Type
    {
        t1,
        t2,
        t3
    };

    Type type;
};

class otherObj
{
public:

    void setType(obj* o);

};

void otherObj::setType(obj* o)
{
    o->type = obj::Type::t1;
    return;
}

How do I do that, because the line

o->type = obj::Type::t1;

throws out an error:

obj::Type is not a class or namespace.
1
  • Your code works for me.
    – Emil Laine
    Mar 8, 2015 at 14:06

3 Answers 3

1
obj::t1
obj::t2
obj::t3

Aren't C++ enums great? The values fall into the scope above them even though the enum can be treated as a type.

0
0

You either just use

obj::t1;

or specify the class attribute with your enum declaration

enum class Type {
    t1,
    t2,
    t3
};
2
  • Actually adding the class attribute didn't fix it. It shows me a warning that I am using C++11 feature, but still doesn't work. Maybe I need to change my compiler settings somewhere?
    – V0ldek
    Mar 8, 2015 at 15:14
  • @V0ldek "It shows me a warning that I am using C++11 feature" You switch on --std=c++11 to fix this, it's the current standard. May be you should look for a more recent c++ compiler, that runs in this mode by default. Mar 8, 2015 at 15:19
0

In C++03, the enum values belong to the enclosing scope. Hence, replacing obj::Type::t1 with obj::t1 would work for you.

This is somewhat counter-intuitive, and is addressed by the enum class feature in C++11, which puts the enum values directly in the enum scope. Thus, if you use enum class in a C++11 compliant compiler, then you would be able to use obj::Type::t1 as you are currently doing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.