Monster Class Sample SolutionΒΆ

#include "cmpt_error.h"
#include <iostream>

using namespace std;

class Monster {
public:
        virtual ~Monster() {} // virtual destructor
        virtual string name() const = 0;
        virtual double health() const = 0;
        virtual void do_damage(double d) = 0;

        void debug_info() const {
                cout << name() << " currently has " << health() << " health\n";
        }
}; // class Monster

class Dragon : public Monster {
private:
        double hp = 100;
        string who;
public:
        Dragon(const string& name)
        : who(name)
        { }

        string name() const { return who; }

    double health() const { return hp; }

    void do_damage(double d) {
                hp -= d;
                if (hp < 0) hp = 0;
        }
}; // class Dragon

class Penguin : public Monster {
private:
        double hp ;
        string who;
public:
        Penguin(const string& name, int hp)
        : hp(hp), who(name)
        { }

        string name() const { return who; }

    double health() const { return hp; }

    void do_damage(double d) {
                hp -= d;
                if (hp < 0) hp = 0;
        }
}; // class Penguin

void report(Monster* m) {
        cout << m->name() << " currently has " << m->health() << " health\n";
}

int main() {
        Dragon d{"Smaug"};
        cout << d.name() << " currently has " << d.health() << " health\n";
        report(&d);
        d.debug_info();

        Penguin p{"Cici", 10};
        cout << p.name() << " currently has " << p.health() << " health\n";
        report(&p);
        p.debug_info();
} // main