Programming lesson
Mastering C++ Structures with Unions and Enums: A May 2026 Guide
Learn how to use C++ structures, unions, and enums to manage movie data, player stats, and worker pay. This tutorial uses timely examples inspired by the 2026 FIFA World Cup and AI trends.
Why Structures Matter in Modern C++ (May 2026)
As we approach the summer of 2026, the programming landscape is buzzing with AI-driven apps and the upcoming FIFA World Cup. But at the core of many systems—from game leaderboards to payroll software—lie fundamental C++ data structures. In this tutorial, you'll learn how to bundle related data using structures, differentiate variants with unions and enums, and write clean, reusable functions. By the end, you'll be able to handle three classic assignment scenarios: movie records, basketball team stats, and worker pay calculations.
Program 1: Movie Data with a Structure
Imagine you're building a database for a film festival like Sundance 2026. Each movie has a title, director, release year, and runtime. Using a struct lets you group these attributes.
Defining the Structure
struct movieData {
string title;
string director;
int year;
int runtime; // in minutes
};Initializing and Displaying
Your main function creates two variables. One uses an initialization list (common in modern C++), the other assigns members one by one.
int main() {
// Initialization list
movieData movie1 = {"War of the Worlds", "Byron Haskin", 1953, 88};
// Member-by-member
movieData movie2;
movie2.title = "War of the Worlds";
movie2.director = "Stephen Spielberg";
movie2.year = 2005;
movie2.runtime = 118;
displayMovie(movie1);
displayMovie(movie2);
return 0;
}The display function takes a const reference to avoid copying and prevent modification:
void displayMovie(const movieData &m) {
cout << "Title: " << m.title << endl;
cout << "Director: " << m.director << endl;
cout << "Released: " << m.year << endl;
cout << "Running Time: " << m.runtime << " minutes" << endl;
}This pattern is everywhere—from AI model metadata to e-sports player profiles. Using const reference is a best practice for performance and safety.
Program 2: Array of Structures – Basketball Team Stats
Now let's scale up. You're managing a basketball team (think NBA playoffs 2026 or a local college league). You need an array of 12 player structures, each with name, number, and points scored.
Structure and Input Function
struct player {
string name;
int number;
int points;
};
void getPlayerData(player &p) {
cout << "Player's name: ";
getline(cin, p.name);
cout << "Player's number: ";
cin >> p.number;
cout << "Points scored: ";
cin >> p.points;
cin.ignore(); // clear newline
}Main Logic: Input, Table, and Top Scorer
int main() {
player team[12];
int totalPoints = 0;
int maxPoints = 0;
int topIndex = 0;
for (int i = 0; i < 12; i++) {
getPlayerData(team[i]);
totalPoints += team[i].points;
if (team[i].points > maxPoints) {
maxPoints = team[i].points;
topIndex = i;
}
}
// Display table
cout << "NAME\tNUMBER\tPTS SCRD" << endl;
for (int i = 0; i < 12; i++) {
cout << team[i].name << "\t"
<< team[i].number << "\t"
<< team[i].points << endl;
}
cout << "TOTAL POINTS: " << totalPoints << endl;
cout << "The player who scored the most points is: "
<< team[topIndex].name << " #" << team[topIndex].number << endl;
return 0;
}This mirrors real-world sports analytics or even gaming leaderboards where you track top performers.
Program 3: Worker Pay with Union and Enum
This is the most advanced part. You need a single structure that can represent either an hourly worker or a salaried worker. The trick: use an enum to track the type, and a union to hold variant data.
Defining the Worker Structure
enum WorkerType { HOURLY, SALARIED };
struct worker {
WorkerType type;
double grossPay;
union {
struct {
double hours;
double rate;
} hourly;
struct {
double salary;
double bonus;
} salaried;
};
};The outer struct has a type field (the enum) and a grossPay field common to both. The anonymous union contains two sub-structures—only one is active at a time.
Input Functions
void getHourly(worker &w) {
w.type = HOURLY;
cout << "Enter the number of hours worked: ";
cin >> w.hourly.hours;
cout << "Enter the hourly pay rate: ";
cin >> w.hourly.rate;
w.grossPay = w.hourly.hours * w.hourly.rate;
}
void getSalaried(worker &w) {
w.type = SALARIED;
cout << "Enter the salary amount: ";
cin >> w.salaried.salary;
cout << "Enter the bonus amount: ";
cin >> w.salaried.bonus;
w.grossPay = w.salaried.salary + w.salaried.bonus;
}Print Function
void printWorker(const worker &w) {
if (w.type == HOURLY) {
cout << "Hourly Worker\n";
cout << "Hours: " << w.hourly.hours << endl;
cout << "Rate: $" << fixed << setprecision(2) << w.hourly.rate << endl;
} else {
cout << "Salaried Worker\n";
cout << "Salary: $" << fixed << setprecision(2) << w.salaried.salary << endl;
cout << "Bonus: $" << fixed << setprecision(2) << w.salaried.bonus << endl;
}
cout << "Gross Pay: $" << fixed << setprecision(2) << w.grossPay << endl;
}Main Driver
int main() {
worker w;
char choice;
cout << "(H)ourly or (S)alaried? ";
cin >> choice;
if (choice == 'H' || choice == 'h') {
getHourly(w);
} else {
getSalaried(w);
}
printWorker(w);
return 0;
}This pattern is used in HR software and payroll systems for companies that have both types of employees. The union saves memory, and the enum ensures you access the correct variant.
Connecting to Trends: AI, Gaming, and Real-World Use
In 2026, AI chatbots like ChatGPT-6 use similar structures to store conversation metadata (user type, session data). Video games like NBA 2K26 use arrays of player structs for rosters. Even finance apps tracking cryptocurrency portfolios use unions for different asset types. Mastering these concepts prepares you for system programming and embedded systems where memory is tight.
Common Mistakes and Debugging Tips
- Forgetting to set the enum type: Always set
w.typein your input functions. Otherwise,printWorkermay read the wrong union member. - Not using
cin.ignore()after numeric input: When mixingcin >>andgetline, always clear the newline to avoid skipping input. - Passing by value instead of reference: For large structs, pass by const reference to avoid expensive copies. For input functions, use a non-const reference.
Conclusion
You've now seen three essential C++ patterns: simple structs, arrays of structs, and structs with unions/enums. These building blocks appear in game development, AI data pipelines, and enterprise software. Practice by adding error checking (e.g., negative points) or expanding the worker struct to include a name. Happy coding in May 2026!