// inheritance and dynamic dispatch demo // cse143 lecture 2/00 hp #include #include using namespace std; // generic Creature class class Creature { public: // construct Creature with given name Creature(string name); // write this Creature's name and sound to cout virtual void speak( ); protected: string name; // this Creature's name }; Creature::Creature(string name) { this->name = name; } void Creature::speak( ) { cout << "A generic creature named " << name << " is mute" << endl; } // Pigs class Pig: public Creature { public: Pig(string name); void speak( ); }; Pig::Pig(string name) : Creature(name) { } void Pig::speak( ) { cout << "A pig named " << name << " says OINK!" << endl; } // Cows class Cow: public Creature { public: Cow(string name); void speak( ); }; Cow::Cow(string name) : Creature(name) { } void Cow::speak( ) { cout << "A cow named " << name << " says Help! I've been tipped and I can't get up!!" << endl; } // test program // produce output from Creature c void talk(Creature &c) { c.speak( ); } // create some Creatures and see what they say int main( ) { Creature fred("Fred"); Pig piggy("Piggy"); Cow boris("Boris"); talk(fred); talk(piggy); talk(boris); cout << endl; return 0; }