Enum is a user-defined datatype. It is a set of integral constants termed as enumerators.
Enum has a limitation. Two enum in a scope cannot have same enumerators. To remove this limitation, C++11 introduced Strongly Typed Enum. Strongly Typed Enum allows you to have enumerators which can be redundant from any other enum. In declaration, a keyword 'class' is added after enum to specify it is a strongly typed enum.
syntax: enum class user-definedDatatype { ....};
Strongly typed enum, provides flexibility at the cost that it has to be used with scope resolution. The surrounding gets corrupted because of redundant enumerators. Hence it is a compilation error to declare or use strongly typed enum without scope resolution. Attached snippet will make it clear
Snippet of the same code to copy and try:
using namespace std;
int main(){
enum class colors { red, blue, aquamarine, yellow };
enum class PrimaryColors { green, blue, red };
enum SecondaryColors { magenta, yellow, cyan };
enum trafficlights { red, /*yellow, */ green }; //yellow is redundant
SecondaryColors sc = yellow;
// colors r = red;
colors r = colors::red;
}
Top comments (0)