Why do virtual enums compile when they cannot be defined in derived class?

Assume this class:

1
2
3
4
5
6
7
8
9
10
11
class GenericTrafficLight {
public:
    virtual enum LightState;

    void setLightState(LightState newState) {
        currentState = newState;
    }

private:
    LightState currentState;
};


And this deriving class:

1
2
3
4
5
6
7
8
9
class FuturisticTrafficLight : public GenericTrafficLight {
public:
    enum LightState {
        LIGHT_STATE_RED = 0,
        LIGHT_STATE_YELLOW = 1,
        LIGHT_STATE_CYAN = 2,
        LIGHT_STATE_GREEN = 3
    };
};


This yields this error: "C2911 (...) cannot be declared or defined in the current scope" in the deriving class's enum definition.

Why is that?
Zyl wrote:
virtual enum


wat?

In all seriousness... I don't think C++ supports virtual enums. Any compiler that is not giving you an error for that probably should be.



Unless this is just some crazy feature I've never heard of before....


What compiler are you using?
Using whatever MSVC 2010 is using I guess. I don't know toolchains. virtual enum statement definitely compiles without warning nor errors. Does not work the way one would expect it to though, heh.

The larger problem is, I have a KeyboardMapper class, where you can basically do things like
1
2
3
KeyboardMapper km;
km.bind(ACTION_WALK_FORWARDS, someotherlibrary::Keyboard::W);
zCoord += km.inAction(ACTION_WALK_FORWARDS) ? 1 : 0;

And that's it. I want people deriving from my KeyboardMapper class to be able to define their own Action enum, which contains ACTION_WALK_FORWARDS as one of its numbers in the above example. What do?
Zyl wrote:
Does not work the way one would expect it to though, heh.
What were you expecting it to work like? Everything I try and think of doesn't make any sense.

As for a solution to your problem...use a std::map<std::string, something_that_represents_a_key>
nvm, just made the enum extern outside of the class scope. Won't have more than one subclass of that per app anyway. Works.

@ how it should work: Cpp is excessively verbose so yeah I guess what makes sense for one is nonsense for another.

@ std map: Oh ancient chinese secret std glory. Eventually I'll come around to read about its standard implementations to common problems. Data structure wasn't the problem though.
GCC reports two errors for this line

virtual enum LightState;

main.cpp:5:18: error: use of enum 'LightState' without previous declaration
main.cpp:5:18: error: 'virtual' can only be specified for functions


So Visual C++ is looking a bit suspect!

Andy

PS And I see this "feature" has made it to Visual C++ 2012.
Last edited on
Topic archived. No new replies allowed.