Constructors
Every hero made from the class so far is Aria with 100 health, because those values are written in the class. A game needs heroes with different names and health, but the members are private, so main can't fill them in. The class needs a way to get its starting values: a constructor.
#include <iostream>
#include <string>
class Hero {
private:
std::string name;
int health;
public:
Hero(std::string heroName, int startHealth) {
name = heroName;
health = startHealth;
}
void printStatus() const {
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 constructor is a method with the name of the class and without a return type, not even void. It runs by itself, once, whenever an object is created. Hero aria("Aria", 100); creates the object aria and passes "Aria" and 100 to the constructor, which stores them in the members. You can also write Hero aria = Hero("Aria", 100); or Hero aria = {"Aria", 100};: with a constructor, braces work again, because they call it. This course uses the first form.
The parameters have names of their own, heroName and startHealth. If a parameter were called name, then inside the constructor, name would mean the parameter and not the member, and name = name; would store the parameter in itself. The member would stay empty, and the program would print heroes without names.
Once a class has a constructor, every object has to be created through it. If you add the line Hero hero; below Finn in the program above, compiling ends with:
main.cpp:23:10: error: no matching constructor for initialization of 'Hero'The notes below the error list the constructors that could have been used, and why none of them fits. The last one is yours: candidate constructor not viable: requires 2 arguments, but 0 were provided. It needs two values and got none. That's good news: a hero without a name and health can't be created by mistake.
Instructions
- 1
Replace the default values of the members with a constructor
Hero(std::string heroName, int startHealth), which stores its parameters in the members. Inmain, create Aria through it, with the nameAriaand100health. The program printsAria: health 100, as before. - 2
Below Aria, create a second hero
finnwith the nameFinnand80health. Finn takes25damage. Then print his status too. The program printsAria: health 100and thenFinn: health 55.