Copies and References
A struct variable holds all its members itself. When you assign it to another variable, C++ copies every member, just as it copies an int or a vector:
#include <iostream>
#include <string>
struct Monster {
std::string name;
int health;
int attack;
};
int main() {
Monster goblin = {"Goblin", 30, 5};
Monster chief = goblin;
chief.name = "Goblin Chief";
chief.health += 20;
std::cout << goblin.name << ": " << goblin.health << std::endl;
std::cout << chief.name << ": " << chief.health << std::endl;
return 0;
}This prints:
Goblin: 30
Goblin Chief: 50chief started as an exact copy of goblin, with a name, health and attack of its own. Changing the copy left the original as it was. That's handy when monsters are alike: copy one and change only what's different.
Assigning to a variable that already exists copies too: after chief = goblin;, the chief has all the goblin's values again, its name included.
When you want another name for the same monster instead of a copy, use a reference, as you did with int& in the lesson on references:
Monster& target = goblin;
target.health -= 12;target isn't a new monster. It's the goblin under another name, so the goblin now has 18 health. A copy or a reference makes a big difference with structs, and you will meet it again in loops and in functions.
Two structs can't be compared with ==. goblin == chief ends with the error invalid operands to binary expression ('Monster' and 'Monster'): C++ doesn't know which members you want to compare. Compare them yourself, such as goblin.name == chief.name.
Instructions
- 1
In place of the comment, create the monster
bossas a copy ofgoblin. Change its name toGoblin Boss, double its health with*=and add3to its attack. Below the line that prints the goblin, print the boss the same way. The program printsGoblin: health 30, attack 5and thenGoblin Boss: health 60, attack 8. Keep the line that creates the goblin as it is: the exercise will also try other values. - 2
At the end of
main(beforereturn 0;), create a referencetargetto the goblin, and lower the goblin's health by12through it, withtarget.health. - 3
Below it, print the goblin once more, with the same line as before. The last line is
Goblin: health 18, attack 5.