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.
- 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.
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.
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)