Structs
Overview
Primitive arrays are powerful, but they have a fatal flaw: they can only hold one single data type. If you want to store a Player in a game, you need an int for their Health, a string for their Name, and a bool for their Status. Storing these in three separate variables is messy and unscalable.
A Struct (Structure) solves this by allowing developers to create custom, User-Defined Data Types. It essentially clumps different primitive variables together into a single, cohesive unit. You can pass a single Player struct to a function instead of passing 3 separate variables.
Syntax
#include <iostream>
#include <string>
// 1. Defining the blueprint for the custom Data Type
struct Player {
std::string name;
int health;
int damage;
};
int main() {
// 2. Creating an 'Instance' (a physical object in memory)
Player p1;
// 3. Accessing members using the Dot Operator (.)
p1.name = "Knight";
p1.health = 100;
// 4. Uniform Initialization (Modern C++ shortcut)
Player p2 = {"Mage", 50, 200};
return 0;
}Common Pitfalls
- Forgetting the semicolon (
;) at the end of the Struct definition. Unlike functions, structurally defining a struct strictly requires a semicolon at the final closing brace:struct X { };. Forgetting this causes the compiler to completely freak out. - Padding and Memory alignment. A struct with a
char(1 byte), then adouble(8 bytes), then achar(1 byte) does NOT take 10 bytes. The CPU adds hidden 'Padding' bytes to align memory for faster access, often inflating the struct size to 24 bytes! Order your variables from largest to smallest to save RAM.
Interview Questions
struct and a class?By absolute definition in C++, they are physically identical in how they operate in memory. The ONLY technical difference is Default Visibility. In a struct, all members are completely public by default. In a class, all members are strictly private by default. Historically, structs are used for simple 'Plain Old Data' (POD) objects, while classes are used for complex OOP behavior.
Real-World Example
Using an Array of Structs to easily manage a database of multiple complex entities.
#include <iostream>
#include <string>
struct Enemy {
std::string type;
int hp;
};
int main() {
// Creating an array of our custom data type!
Enemy horde[3] = {
{"Goblin", 30},
{"Orc", 100},
{"Troll", 250}
};
// Blazing fast access to structured data
for (int i = 0; i < 3; i++) {
std::cout << horde[i].type << " HP: " << horde[i].hp << "\n";
}
return 0;
}Check Your Knowledge
Test your understanding of Structs with these quick questions.