Search code examples
c++forward-declarationenum-class

Forward declared enum as class member variable


As a rule of thumb on forward declaration (from "API Design for C++", p. 214), I only include the header of a class if I:

  • use an object of that class as a data member in my own class, or
  • inherit from that class.

In all rest cases I just forward declare the class.

However, I recently used by accident as a data member of a class a forward declared enum class, and it compiled.

Is this indeed ok to use, or a just an accidental hack (and I actually need the header with the definition of MyEnum)?

// test.hpp
enum class MyEnum;

class A {
    MyEnum myenum;
};

Solution

  • A forward declared enum class has a specified underlying type. If not explicitly specified it is int. Because of that the storage size of the enum is known, even if it's only forward declared, so using it as a member is not a problem.