0

Suppose I have the following enum inside class

class A
{
    enum E {a,b};
};

I know that since c++11 we can forward declare enum, because it's default type is int. But how can I forward declare enum E of class A in case class A is only declared and not defined?

And if it is not possible then why?

Vahag Chakhoyan
  • 873
  • 1
  • 10
  • 21

1 Answers1

2

I know that since c++11 we can forward declare enum, because it's default type is int.

Not quite. You can only forward declare an enum when the underlying type is explicitly specified. This is not allowed:

enum A;
enum A { X,Y};   // not allowed

With gcc the error message is still a little misleading, stating that it would be disallowed to forward declare enums in general which isn't correct anymore (https://godbolt.org/z/xYb5cKEWP).

This is ok

enum A : int;
enum A : int { X,Y};

Note that the default is not simply int. From cppreference:

[...] the underlying type is an implementation-defined integral type that can represent all enumerator values; this type is not larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. If no integral type can represent all the enumerator values, the enumeration is ill-formed

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • I don't think this answers the question. Now try this when, as the question describes, the enum is an inner class member. "But how can I forward declare enum E of class A in case class A is only declared and not defined?" – Sam Varshavchik Aug 31 '22 at 16:38
  • @Sam the answer is no because you cannot forward declare `enum E {a,b}` whether inside a class or not. Though I agree that this answer fails to explain the case of `class A { enum E : int {a,b} };`. Just cannot fix it now – 463035818_is_not_an_ai Aug 31 '22 at 16:42