/* polytest.cpp CIS 250 4/13/09 Dave Klick Class used to demonstrate inheritance, polymorphism, and virtual functions. */ #include #include #include #include using std::cout; using std::endl; using std::string; class Name { private: string name; public: Name() : name("") { } Name(const char* str) : name(str) { } const string getName() const { return name; } void setName(const char* nm) { name = nm; } }; class Animal { public: Name name; Animal() : name("") {} Animal(const char* s) : name(s) {} virtual void speak() const = 0; virtual void print() const = 0; virtual void setSpeech(const char*) = 0; const string getName() const { return name.getName(); } void setName(const char* nm) { name.setName(nm); } }; class Dog : public Animal { string speech; public: Dog() : Animal("Fido"), speech("Woof") {} Dog(const char* nm) : Animal(nm), speech("Woof") {} void setSpeech(const char* s) { speech = s; } const string getSpeech() { return speech; } void print() const { cout << "Dog named " << name.getName() << " says " << speech; } void speak() const { cout << speech << endl; } }; class Cat : public Animal { string speech; public: Cat() : Animal("Tiger"), speech("Meow") {} Cat(const char* nm) : Animal(nm), speech("Meow") {} void setSpeech(const char* s) { speech = s; } const string getSpeech() { return speech; } void print() const { cout << "The cat (" << name.getName() << ") says " << speech; } void speak() const { cout << speech << endl; } }; int main(void) { srand(time(NULL)); int i; char* names[] = { "Freddie", "Bobbie", "Killer", "Sammy", "Champs", "Blue", "Rambo", "Kitty", "Clyde", "Annie", "Kelly", "Kitty", "Trouble", "Krissy" }; char* sayings[] = { "Arf", "Hi", "Purr", "Wassup" }; Animal* pets[20]; for (i=0; i<20; i++) { int type = rand() % 2; int r = rand() % 14; if (type == 0) { pets[i] = new Cat(names[r]); } else { pets[i] = new Dog(names[r]); } } for (i=0; i<20; i++) { int n = rand() % 3; if (n == 0) { int x = rand() % 4; pets[i]->setSpeech(sayings[x]); } } for (i=0; i<20; i++) { pets[i]->print(); cout << endl; } for (i=0; i<20; i++) pets[i]->speak(); system("pause"); return 0; }