C++
Module 18: Structures, Unions, and EnumerationsIntermediate40 min read

Structs, Unions & Scoped Enumerations (enum class)

Compare struct vs class in C++, understand union shared memory layout, and prefer type-safe C++11 enum class over unscoped enums.

Key Takeaways & Core Concepts
  • for type-safe tagged unions.
  • for strong type safety.

1. `struct` vs. `class`

In C++, struct defaults to public members and inheritance; class defaults to private. Use struct for passive data aggregates (PODs) and class for invariant-enforcing abstractions.

1. Designated Initializers (C++20) & enum class
1#include <iostream>
2enum class HttpStatus : int { Ok = 200, BadRequest = 400 };
3struct Config { int port = 8080; bool tls = true; };
4
5int main() {
6 Config cfg{.port = 9000, .tls = false};
7 std::cout << "Port: " << cfg.port << ", Status: " << static_cast<int>(HttpStatus::Ok) << "\n";
8 return 0;
9}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: Shows C++20 designated initializers and underlying-typed `enum class`.

2. `union` vs. `std::variant` (C++17)

A union overlays all members at the same memory address (size = largest member). Reading an inactive member is Undefined Behavior. In Modern C++, use `std::variant` for type-safe tagged unions.

3. Traditional `enum` vs. `enum class` (C++11)

Traditional enums leak enumerators into the enclosing scope and implicitly convert to int. Always prefer `enum class` for strong type safety.

Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)