Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Quiz: Damage in a Loop

This program should take 10 health from each monster and then print 20 and 40, but it doesn't compile. Click the line with the mistake.

1#include <iostream>
2#include <string>
3#include <vector>
4
5class Monster {
6private:
7    std::string name;
8    int health;
9
10public:
11    Monster(std::string monsterName, int startHealth) {
12        name = monsterName;
13        health = startHealth;
14    }
15
16    void takeDamage(int amount) {
17        health -= amount;
18    }
19
20    int getHealth() const {
21        return health;
22    }
23};
24
25int main() {
26    std::vector<Monster> monsters = {Monster("Goblin", 30), Monster("Orc", 50)};
27    for (const Monster& monster : monsters) {
28        monster.takeDamage(10);
29    }
30    for (const Monster& monster : monsters) {
31        std::cout << monster.getHealth() << std::endl;
32    }
33    return 0;
34}
Back

10/11

  1. 1. Methods
  2. 2. Methods That Change the Object
  3. 3. Private and Public Members
  4. 4. Getters and const Methods
  5. 5. Constructors
  6. 6. Quiz: Constructors
  7. 7. Rules in One Place
  8. 8. Objects as Parameters
  9. 9. A Vector of Objects
  10. 10. Quiz: Damage in a Loop
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.