project3 soln

# project3 soln - Homework 3 Solution Problem 1 Problem 3...

This preview shows pages 1–3. Sign up to view the full content.

Homework 3 Solution Problem 1 Problem 3 Problem 2 Problem 4 Problem 1: Since all Creatures have a name, and since the way you find out the name is going to be the same for all kinds of creatures, the name should be a data member of Creature, and the function to retrieve it need not be virtual. The different kinds of creatures may have different ways of moving, and may or may not be mortal, so these functions should be virtual. Since most creatures are mortal, it's convenient to have Creature::mortal have an implementation (that returns true) that derived classes may inherit if they wish. There is no reasonable default behavior for move, so this should be pure virtual. Observe how the constructors for the derived classes pass the name to the Creature constructor. Examine Giant's constructor especially. // ======================================= Creature class Creature { public: Creature(string nm); string name() const; virtual string move() const = 0; virtual bool mortal() const; virtual ~Creature() {} private: string m_name; }; Creature::Creature(string nm) : m_name(nm) {} string Creature::name() const { return m_name; } bool Creature::mortal() const { return true; } // ======================================= Phoenix class Phoenix : public Creature { public: Phoenix(string nm); virtual string move() const; virtual bool mortal() const; virtual ~Phoenix(); };

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Phoenix::Phoenix(string nm) : Creature(nm) {} string Phoenix::move() const { return "fly"; } bool Phoenix::mortal() const { return false; } Phoenix::~Phoenix() { cout << "Destroying " << name() << " the phoenix." << endl; } // ======================================= Giant class Giant : public Creature { public: Giant(string nm, int wt); virtual string move() const; virtual ~Giant(); private: int m_weight; }; Giant::Giant(string nm, int wt) : Creature(nm), m_weight(wt) {} string Giant::move() const { if (m_weight < 20) return "tromp"; else return "lumber"; } Giant::~Giant() { cout << "Destroying " << name() << " the giant." << endl; } // ======================================= Centaur
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 01/24/2012 for the course CS CS 32 taught by Professor Mojavi during the Spring '08 term at UCLA.

### Page1 / 7

project3 soln - Homework 3 Solution Problem 1 Problem 3...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online