C++ · Module 17 · Lesson 21 min read

enum class, Aliases & Attributes

Old enums vs enum class

arduino
enum Color { Red, Green };          // unscoped: names leak, converts to int silently
enum class Category { Food, Rent }; // scoped ✅
Category c = Category::Food;
int x = c;                          // ❌ error: no implicit conversion
int y = static_cast<int>(c);        // ✅ explicit
enumenum class
Names scopedno (Red)yes (Category::Food)
Implicit int conversionyes ⚠️no ✅
Same name in two enumsconflictfine

Underlying type

enum class Status : std::uint8_t { Active, Blocked }; — choose the storage size (useful for files and networking).

using enum (C++20)

Inside a switch: using enum Category; lets you write Food instead of Category::Food.

Enum ↔ string

C++ has no built-in reflection (yet), so write a to_string with a switch, or a constexpr std::array of names.

Flags with enum class

Overload | and & for an enum to combine options safely.

Type aliases

arduino
using Money = long long;                       // ✅ modern
typedef long long Money;                       // old style
template <typename T> using Grid = std::vector<std::vector<T>>;   // alias templates (typedef can't)

Standard attributes

AttributeMeaning
[[nodiscard]]warn if the return value is ignored
[[nodiscard("reason")]]with a message (C++20)
[[maybe_unused]]silence "unused" warnings
[[fallthrough]]intentional switch fall-through
[[deprecated("use X")]]warn when used
[[likely]] / [[unlikely]]branch hints (C++20)
[[noreturn]]function never returns (e.g. always throws/exits)
[[assume(expr)]]optimization hint (C++23)

Example

C++
#include <array>
#include <cstdint>
#include <iostream>
#include <string_view>
#include <vector>

enum class Category : std::uint8_t { Food, Rent, Travel, Fun };
constexpr std::array<std::string_view, 4> CATEGORY_NAMES = { "Food", "Rent", "Travel", "Fun" };

constexpr std::string_view to_string(Category c) { return CATEGORY_NAMES[static_cast<std::size_t>(c)]; }

enum class Permission : unsigned { None = 0, Read = 1, Write = 2, Share = 4 };
constexpr Permission operator|(Permission a, Permission b) {
    return static_cast<Permission>(static_cast<unsigned>(a) | static_cast<unsigned>(b));
}
constexpr bool has(Permission set, Permission p) { return (static_cast<unsigned>(set) & static_cast<unsigned>(p)) != 0; }

using Money = long long;                                  // paisa
template <typename T> using Grid = std::vector<std::vector<T>>;

[[nodiscard]] Money monthly_limit(Category c) {
    switch (c) {
        using enum Category;                              // C++20: no Category:: prefix needed
        case Food:   return 600000;
        case Rent:   return 1500000;
        case Travel: return 200000;
        case Fun:    return 150000;
    }
    return 0;
}

[[deprecated("use monthly_limit instead")]] Money old_limit() { return 0; }

[[noreturn]] void fail(std::string_view msg) {
    std::cerr << "fatal: " << msg << '\n';
    std::exit(1);
}

int main() {
    Category c = Category::Travel;
    // int bad = c;                                       // error: no implicit conversion
    std::cout << to_string(c) << " has value " << static_cast<int>(c)
              << " and sizeof " << sizeof(Category) << " byte\n";

    for (auto cat : { Category::Food, Category::Rent, Category::Fun })
        std::cout << to_string(cat) << " limit: Rs. " << monthly_limit(cat) / 100 << '\n';
    // monthly_limit(Category::Food);                     // warning: ignoring [[nodiscard]] return value

    Permission p = Permission::Read | Permission::Share;
    std::cout << std::boolalpha << "can read? " << has(p, Permission::Read)
              << ", can write? " << has(p, Permission::Write) << '\n';

    Grid<int> seats(2, std::vector<int>(3, 0));
    [[maybe_unused]] int debug_only = 42;                 // no unused-variable warning
    std::cout << "grid " << seats.size() << "x" << seats[0].size() << '\n';

    int balance = 500;
    if (balance < 0) [[unlikely]] fail("negative balance");
    std::cout << "balance ok\n";
    return 0;
}

/* Output:
Travel has value 2 and sizeof 1 byte
Food limit: Rs. 6000
Rent limit: Rs. 15000
Fun limit: Rs. 1500
can read? true, can write? false
grid 2x3
balance ok
*/