Search code examples
c++11enumsforward-declaration

forward declaration of enum in base class, definition in derived class


So, I am trying to define an enum in a derived class where the declaration is in the base class. It looks something like this:

class A {
    public:
    enum class E;
    virtual int foo () = 0;
};

class B : public A {
    public:
    enum class E { C, D };
    int foo () {
        E e = E::C;
        return 0;
    }
};

int main() {
    B b;
    A *a = &b;
    a->foo();
}

This will work (compiler gcc 4.8, compile command: g++ -std=c++11 ...) however I was wondering if there is a better way to do this, so that I don't have to write E:: everytime I have to use the enum.

edit: I mistakenly thought this works, however, this is not really a forward declartion but two distinct enum class A::E and B::E


Solution

  • I was wondering if there is a better way to do this, so that I don't have to write E:: everytime I have to use the enum.

    This is unrelated to forward declaration. You have to write E::, because you use enum class.
    If you don't want this, use old enum instead:

    class B : public A {
        public:
        enum E { C, D };
        // ...
    };