So far, we’ve worked with single variables (like an int) or collections of the same type (Arrays). But what if you want to represent a "Student" who has a name (string), an age (int), and a GPA (double)?
A Structure (or struct) allows you to group different data types together under one name. It is a user-defined data type that represents a "record."
1. Defining and Using a Struct
Members: The variables inside the struct are called members or fields.
The Dot Operator (
.): You use a period to access specific members of a struct variable.
Code Example: Managing a Game Character
This program defines a Character struct and creates a variable to store its stats.
#include <iostream>
#include <string>
using namespace std;
// 1. Defining the Structure (The Blueprint)
struct Player {
string name;
int level;
float health;
bool isAlive;
};
int main() {
// 2. Creating an instance of the struct
Player player1;
// 3. Assigning values using the Dot (.) Operator
player1.name = "DragonSlayer";
player1.level = 15;
player1.health = 95.5f;
player1.isAlive = true;
// 4. Accessing values
cout << "--- Player Stats ---" << endl;
cout << "Name: " << player1.name << endl;
cout << "Level: " << player1.level << endl;
cout << "Health: " << player1.health << endl;
// 5. Array of structs (Creating a team)
Player team[2] = {
{"Archer", 10, 80.0, true},
{"Mage", 12, 60.5, true}
};
cout << "\nTeammate 1: " << team[0].name << " (Lvl " << team[0].level << ")" << endl;
return 0;
}Why use struct?
Organization: It keeps related data together, making the code much easier to read.
Function Parameters: Instead of passing 5 different variables to a function, you can just pass one
struct.
Pro Tip: Structs vs. Classes
In C++, a struct is almost identical to a class. The only major difference is that by default, everything in a struct is public (anyone can access it), while in a class, everything is private (hidden).