/* * This code is written all in one file for instructional simplicity only; you should always split * your code into separate header files */ #include #include using namespace std; class Animal { public: virtual void describe() = 0; bool isAlive(); Animal(bool isAlive); virtual ~Animal(); private: bool isAlive_; }; class Monkey : public Animal { public: void describe(); Monkey(); ~Monkey(); }; class Parrot : public Animal { public: void describe(); Parrot(); ~Parrot(); }; Animal::Animal(bool isAlive) : isAlive_(isAlive) {} Animal::~Animal() { cout << "cleaning cage" << endl; } bool Animal::isAlive() { return isAlive_; } /* Note that another way we could have fixed this would be to add a default * constructor for Animal. The downside to that solution is that if the default * didn't do the right initialization, the compiler wouldn't issue a warning * and something would likely go wrong at runtime. So if you're inheriting * from a class with a default constructor, it's best to just get in the habit * of always explicitly calling the base class constructor, even if it's the * default. */ Monkey::Monkey() : Animal(true) {} Monkey::~Monkey() { cout << "releasing tree branches" << endl; } void Monkey::describe() { cout << "A monkey!" << endl; } Parrot::Parrot() : Animal(true){} Parrot::~Parrot() { cout << "Flying away" << endl; } void Parrot::describe() { cout << "A many-colored parrot" << endl; } int main() { list l; l.push_back(new Monkey()); l.push_back(new Parrot()); list::iterator it; for (it = l.begin(); it != l.end(); it++) { (*it)->describe(); cout << "This animal is alive: " << (*it)->isAlive() << endl; delete (*it); } return 0; }