Structures
In this lesson, you learn how to create data types made up of many smaller elements - what in C++ we call structures.
Motivation
Goblin image by LuizMeloIf, for example, when creating a game 🎮, we want to include opponents in our program, we will usually have to write down some information about each of them.
Consider what data about the enemies in the game can be useful? It can be, for example:
- name 👾
- health 💚
- strength 💪
etc.
Using the knowledge we have acquired so far, if we wanted to write a program that stores this information, we could do it like this:
#include <string>
int main() {
std::string enemy_name = "Goblin";
float enemy_health = 50;
float enemy_strength = 12;
// ...
}
When we want to have more opponents in the game, we will encounter a problem, or rather inconvenience:
If we use multiple arrays for this purpose:
std::vector< std::string > enemy_names;
std::vector< float > enemy_health;
std::vector< float > enemy_strength;
then each opponent will be described under the same index in these tables:
enemy_names[ index ]
describes the nameenemy_health[ index ]
describes life pointsenemy_strength[ index ]
describes the points of strength
This method involves "spreading" information about a single opponent across multiple tables.
Adding one enemy to a set in such a program would look like this:
enemy_names.push_back("Goblin");
enemy_health.push_back(50);
enemy_strength.push_back(10);
The more information we want to store about our opponents, the more bothersome it will be. Fortunately, structures come to our aid here.
Creating structures
Let's recall what data we need to store:
- name 👾
- life 💚
- strength 💪
We are about to add a structure that allows us to create an object that contains these 3 things.
#include <string>
struct Enemy
{
std::string name;
float health;
float strength;
};
int main()
{
// We leave it empty for now
}
The above code introduces a new structure - Enemy
.
A structure is a description, a pattern, a recipe for how to create an object (in this case, an enemy).
To create a structure, we write its name after the struct
keyword, then we put its contents
between the curly braces {
and }
.
The contents can be, for example, variables.
Note the obligatory semicolon after the curly braces to close the structure definition:
struct Enemy
{
std::string name;
float health;
float strength;
};