Braces and Default Values
Filling in the members one by one takes a line for each of them. You can also give a struct all its values at once, in curly braces, when you create it:
Monster goblin = {"Goblin", 30, 5};The values go into the members in the order in which the definition lists them: "Goblin" into name, 30 into health and 5 into attack. So the order matters. With the name in the wrong place, {30, "Goblin", 5}, the program doesn't compile, and the first error says that a number can't become a string:
main.cpp:11:23: error: no viable conversion from 'int' to 'std::string' (aka 'basic_string<char>')Swapping two members of the same type is worse. {"Goblin", 5, 30} compiles without a word, and you get a goblin with 5 health and an attack of 30. When the values are numbers, check their order against the definition.
When you give fewer values than the struct has members, the rest are empty: numbers are 0 and strings have no characters. Monster slime = {"Slime"}; is a slime with 0 health and 0 attack.
Often a member has a usual value. You can write it into the definition as a default value:
struct Hero {
std::string name;
int health = 100;
int gold = 0;
};Every hero now starts with 100 health and no gold, unless you say otherwise. Values in braces replace the default values, from the left:
Hero aria = {"Aria"};
Hero rich = {"Midas", 80, 999};
std::cout << aria.name << ": " << aria.health << " health, " << aria.gold << " gold" << std::endl;
std::cout << rich.name << ": " << rich.health << " health, " << rich.gold << " gold" << std::endl;This prints:
Aria: 100 health, 0 gold
Midas: 80 health, 999 goldEven Hero nobody;, without any braces, has 100 health and 0 gold. In Monster goblin;, on the other hand, the numbers hold nonsense until you assign them a value, just like an int variable created without a value. So give your members default values, or create the variable with braces.
Like a vector, a struct can't be printed whole. std::cout << goblin ends with a long error that starts like this:
main.cpp:12:15: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'Monster')C++ doesn't know how a monster should look in the output. Print its members one by one.
Instructions
- 1
Create the goblin in one line: replace the four lines that create it and fill in its members with one line that gives it all three values in braces. The program still prints
Goblin: health 30, attack 5. - 2
The orc gets only its name, so its health and attack are
0. In the struct, givehealththe default value100andattackthe default value10. Don't change the line that creates the orc. The program then printsOrc: health 100, attack 10, and the goblin keeps its own values.