Methods
In the Structs lesson, you put everything that belongs to a monster into one type: its name, its health and its attack. In this lesson, your types also get behavior: functions of their own that work with their members. And you will learn to protect the members, so that no other part of the program can put them into a wrong state. That's what classes are for.
So far, a function that works with a struct stood outside it, and you passed the struct to it as a parameter. C++ lets you write the function inside the struct instead:
#include <iostream>
#include <string>
struct Hero {
std::string name;
int health;
void printStatus() {
std::cout << name << ": health " << health << std::endl;
}
};
int main() {
Hero aria = {"Aria", 100};
Hero finn = {"Finn", 80};
aria.printStatus();
finn.printStatus();
return 0;
}This prints:
Aria: health 100
Finn: health 80A function written inside a struct is called a method. You know the word from the lesson on vectors, where names.size() calls the method size() of the vector names. Now you write methods of your own, and you call them the same way, with a dot: aria.printStatus().
A variable of a struct's type, such as aria, is called an object. Inside a method, the names of the members mean the members of the object the method was called on, the one before the dot. In aria.printStatus(), name and health are Aria's, and in finn.printStatus(), they are Finn's. That's why the method has no parameter: it already knows its object.
The braces still fill in the members, in order: {"Aria", 100}. A method isn't one of the values, so it doesn't change how you create an object.
A method exists only together with an object. If you write printStatus(); in place of aria.printStatus(); in the program above, as if it were an ordinary function, the compiler doesn't know it:
main.cpp:16:5: error: use of undeclared identifier 'printStatus'Instructions
- 1
Turn the function
printMonsterinto a methodprintStatus()of the structMonster: move it into the struct, below the members, remove its parameter and use the members directly, withoutmonster.in front of them. Inmain, callgoblin.printStatus()instead of the function. The program still printsGoblin: health 30, attack 5. - 2
Below that, create a second monster
orcwith the nameOrc,50health and the attack8, and print it with its method too. The program printsGoblin: health 30, attack 5and thenOrc: health 50, attack 8. Keep the goblin's line as it is: the exercise will also try other values.