C++ from Basics to Mastery — Part 6
When to use structures and classes?
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
So far, we have learned about variables and functions. However, it is quite cumbersome to manage the monster ID, name, and stamina separately as variables while making a game.
int monsterId = 1;
std::string monsterName = "Slime";
int monsterHealth = 30;
If there are 100 monsters, the variables will continue to increase. In this case, structures are used to group related data together.
struct
#include <string>
struct Item
{
int id;
std::string name;
int price;
};
Item sword{1, "Sword", 100};
Item sword{1, "Sword", 100};The method of putting members in order using curly braces is called aggregate initialization. A structure is not a special chunk of memory. It is a user-defined type that groups related values with names.
void PrintItem(const Item& item)
{
std::cout << item.name << '\n';
}
Item MakePotion()
{
return Item{2, "Potion", 50};
}
Structures can also be passed as arguments to functions or returned as values.std::vector<Item>It can also be stored in the same container.
class
If you just put data in the structure, the physical strength can be changed to a strange value from the outside.
monster.health = -9999;
good night. It compiles, but the monster's state is broken. To prevent this from happening, tie data and operations that change data to the same class.
#include <algorithm>
#include <string>
class Monster
{
public:
Monster(int id, const std::string& name, int health)
: id(id), name(name), health(health)
{
}
void TakeDamage(int damage)
{
health = std::max(0, health - damage);
}
int GetHealth() const
{
return health;
}
const std::string& GetName() const
{
return name;
}
private:
int id;
std::string name;
int health;
};
publicis the part to be disclosed to the outside,privateis a part to be used only inside the class. Hiding member variables as private and changing their state through public functions is called encapsulation.
after the constructor: id(id), name(name), health(health)is the constructor initialization list. Rather than assigning values after an object is created, members are initialized the moment they are created.
Structures and classes seem like completely different things, but in C++, the biggest difference is that the default access specifiers are different. A struct is public by default, and a class is private by default.
For simple purposes of grouping values, struct is convenient. If you want to protect the state and bind actions, a class is more natural.