Structures
Learn to group related data together using structures, the foundation for object-oriented programming in C++
Learn how to bundle related data together using structures, creating custom data types that model real-world entities.
A Simple Example
#include <iostream>
#include <string>
struct Player {
std::string name;
int health;
int level;
double x, y; // Position coordinates
};
int main() {
// Create a Player instance
Player hero;
hero.name = "Aria";
hero.health = 100;
hero.level = 5;
hero.x = 10.5;
hero.y = 20.3;
std::cout << hero.name << " is at level " << hero.level << "\n";
std::cout << "Health: " << hero.health << "\n";
std::cout << "Position: (" << hero.x << ", " << hero.y << ")" << "\n";
// Uniform initialization (modern C++)
Player villain{"Dark Lord", 150, 10, 50.0, 75.0};
std::cout << "\nEnemy: " << villain.name << " (Level " << villain.level << ")" << "\n";
return 0;
}
Breaking It Down
Defining a Structure
- What it does: Creates a custom data type that groups related variables together
-
Syntax:
struct Name { members; };- note the semicolon at the end - Members: Can be any data type - int, double, string, even other structs
- Remember: Structures define a blueprint, not an actual variable yet
Creating and Using Struct Instances
-
Declaration:
Player hero;creates an instance of the Player struct -
Access members: Use the dot operator
.to access fields (e.g.,hero.name) - Assign values: Each member can be assigned individually
- Remember: Each instance is a separate copy with its own values
Uniform Initialization with Structs
- What it does: Initialize all members in one line using braces
-
Syntax:
Player villain{"Dark Lord", 150, 10, 50.0, 75.0}; - Order matters: Values must match the order members were declared
- Remember: This is cleaner and safer than assigning each member separately
Public by Default
- What it means: All struct members are accessible from anywhere
- No access specifiers needed: Unlike classes, structs default to public
- Use for: Simple data containers without complex behavior
- Remember: Structs are "data bags" - classes are for objects with methods
Why This Matters
- Real-world entities have multiple properties - a player has a name, health, and position; a book has a title, author, and page count.
- Structures let you model these complex entities as single units instead of juggling separate variables.
- This is the first step toward object-oriented programming and is fundamental to writing organized, professional code.
Critical Insight
Structures are public by default, meaning all members are accessible from anywhere. This makes them perfect for simple data containers. Later, you will learn about classes, which default to private members and add methods.
But structures are ideal when you just need to bundle data together without complex behavior - think of them as "data bags" rather than complete objects. They let you pass around related data as a single unit instead of juggling multiple variables.
Best Practices
Always end struct definitions with a semicolon: struct Name { ... }; - forgetting this causes cryptic compiler errors.
Initialize struct members: Use uniform initialization Player p{"Name", 100, 1, 0.0, 0.0}; or initialize individually to avoid garbage values.
Use meaningful struct names: Name structs after what they represent (Player, Book, Point) not generic names like Data or Info.
Group related data only: Keep structs focused on one concept - do not mix unrelated fields together.
Common Mistakes
Forgetting semicolon: The struct definition must end with a semicolon. Missing it causes "expected ; after struct definition" errors.
Not initializing members: Uninitialized struct members contain garbage values. Always initialize before use.
Passing large structs by value: Copying large structures is slow. Use references or pointers for better performance.
Wrong initialization order: When using uniform initialization, values must match the order members were declared in the struct.
Debug Challenge
This struct definition has a common syntax error. Click the highlighted line to fix it:
Quick Quiz
- How do you access a member of a structure?
- What is the default access level for struct members?
- Can a struct contain different data types?
Practice Playground
Time to try out what you just learned! Play with the example code below, experiment by making changes and running the code to deepen your understanding.
Output:
Error:
Lesson Progress
- Fix This Code
- Quick Quiz
- Practice Playground - run once