🧱 Structures and Enums in C++ — Group Data Like a Pro
Master C++ structures (struct) and enumerations (enum, enum class). Bundle related data, define readable constants and avoid type-safety pitfalls — with examples.
A struct groups related variables under one name. An enum defines a named set of integer constants.
🧱 struct — custom data type
struct Point {
double x;
double y;
};
Point p = {3.0, 4.0};
std::cout << p.x << ',' << p.y;🆕 enum class (C++11+) — strongly typed
enum class Color { Red, Green, Blue };
Color c = Color::Red;
// int i = c; // ❌ no implicit conversion🆚 struct vs class
Same thing — members are public by default in struct, private by default in class. Use struct for simple data bundles, class when you have methods + state.
💻 Code Examples
A struct with multiple members
struct User {
std::string name;
int age;
bool isAdmin;
};
User u = {"Sam", 28, true};
std::cout << u.name << ' ' << u.age;Output:
Sam 28
enum class for type safety
enum class Direction { North, South, East, West };
Direction d = Direction::North;
if (d == Direction::North) std::cout << "heading north";Output:
heading north
⚠️ Common Mistakes
- Using plain `enum` and accidentally treating it as an int.
- Forgetting that struct's default access is public — surprising if you came from Java.
- Trying to compare enum class values with == across different enum classes — won't compile (good).
- Adding methods to struct and not realizing struct/class are the same — fine, but pick a style and be consistent.
🎯 Interview Questions
Real questions asked at top product and service-based companies.
Q1.What's the difference between struct and class in C++?Beginner
Identical except for default access: struct members are PUBLIC by default, class members are PRIVATE. Convention: use struct for passive data, class when methods + invariants are involved.
Q2.What is an enum used for?Beginner
To give names to a group of related integer constants — making code self-documenting.
Q3.Why prefer enum class over plain enum?Intermediate
enum class is SCOPED (members accessed via `Color::Red`, not just `Red`) and STRONGLY TYPED (no implicit conversion to int). Prevents name collisions and accidental integer comparisons.
Q4.How do you specify the underlying type of an enum?Intermediate
`enum class Color : uint8_t { Red, Green, Blue };` — useful when serializing or matching a wire format. Default is int.
Q5.Are structs in C++ POD types (Plain Old Data)?Advanced
Only if they have no user-defined constructors, destructors, virtual functions, or non-public members. POD types can be safely memcpy'd and follow C's layout rules.
🧠 Quick Summary
- struct bundles related data; public by default.
- class is the same but private by default.
- enum gives names to integer constants.
- Prefer enum class — scoped and type-safe.
- Use struct for plain data; class for data + behavior.