Vahag Chakhoyan
Vahag Chakhoyan

Reputation: 779

c++ forward declare enum of class

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?

Upvotes: 0

Views: 326

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

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

Upvotes: 2

Related Questions