Skip to content

enum class (C++11) ​

In a Nutshell ​

A scoped enumeration type that fixes the two classic problems of plain enum: enumerator names polluting the global namespace, and implicit conversion to integers.

No header required (language keyword)

Core API Cheat Sheet ​

OperationSignatureDescription
Declarationenum class Name { A, B, C };Basic scoped enum; the underlying type defaults to int
Specify the underlying typeenum class Name : uint8_t { A, B };Pins down the underlying type, saving memory
Access an enumeratorName::AMust be accessed through the scope operator
Convert to an integerstatic_cast<int>(Name::A)Explicit cast required; no implicit conversion
Opaque declarationenum class Name : uint8_t;Forward declaration; the underlying type must be specified
using enumusing enum Name;(C++20) Brings the enumerators into the current scope

Minimal Example ​

C++
// Standard: C++11
#include <cstdint>
#include <iostream>

int main() {
    enum class Color : uint8_t { red, green = 20, blue };
    Color r = Color::blue;

    switch (r) {
        case Color::red:   std::cout << "red\n";   break;
        case Color::green: std::cout << "green\n"; break;
        case Color::blue:  std::cout << "blue\n";  break;
    }

    // int n = r; // error
    int n = static_cast<int>(r);
    std::cout << n << '\n'; // 21
}

Embedded Applicability: High ​

  • Specifying the underlying type (e.g., uint8_t, uint32_t) gives you exact control over memory footprint, a good fit for protocol parsing and register mapping
  • Zero runtime overhead; everything is fully resolved at compile time
  • Eliminates naming conflicts, which suits modular development in large embedded projects
  • Requiring an explicit cast rules out accidental integer comparisons, improving code safety

Compiler Support ​

GCCClangMSVC
4.73.12010

See Also ​


Part of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05