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: Constructors

What does this program print?

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

6/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.