0

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;
};
gmargari
  • 171
  • 1
  • 9

1 Answers1

2

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.

super
  • 12,335
  • 2
  • 19
  • 29
  • But if the actual enum definition has a specified type (or it is changed later, after I have forward-declared the enum in my file), e.g. `enum class MyEnum: char { VAL1, VAL2 };` will this still be ok? – gmargari Apr 10 '20 at 08:29
  • That's not allowed. If the type is not specified in the forward declaration it is `int`. – super Apr 10 '20 at 08:30
  • So, if initially the type was not specified in definition, everything is ok. If later someone specifies the enum type in definition to be `char`, will she get a compilation error? Also, will all forward declarations need to be changed to also specify the underlying enum type? – gmargari Apr 10 '20 at 08:35
  • Yes. [Live example](https://wandbox.org/permlink/NraFXFB1cbJVx2GJ). – super Apr 10 '20 at 08:36