This implementation uses several files to implement the inheritance. The “Cat” class inherits from the “Animal” class but overrides the “move” function. When “Animal”s and “Cat”s are put in a vector, polymorphic behavior is exhibited depending on the class of the instance.
— creatures.cpp —
#include <iostream> #include <fstream> #include <vector> #include <sstream> #include <string> #include "Animal.h" #include "Cat.h" int main() { Animal bug(6); bug.move(); bug.crawl(); Cat kitty; kitty.move(); kitty.crawl(); cout << "Now we will try polymophism"<<endl; vector <Animal *> avec; avec.push_back(&bug); avec.push_back(&kitty); avec[0]->move(); // This call will have the normal Animal Behavior avec[1]->move(); // This call will have the Cat Behavior even though the vector holds Animals system("pause"); }
— Animal.h —
#ifndef ANIMAL_H #define ANIMAL_H #include "utilities.h" class Animal { public: Animal(); Animal(int legs); virtual void move(); // The virtual syntax tells the compiler to use the subclass implementation if it exists. void crawl(); private: int legs; }; #endif
— Animal.cpp —
#include "Animal.h" void Animal::move() { cout << "Move Move"<<endl; } void Animal::crawl() { cout << "I have "<<legs<<" Legs"<<endl; } Animal::Animal() { legs = 4; } Animal::Animal(int legs) { this->legs = legs; }
— Cat.h —
#pragma once #include "Animal.h" class Cat : public Animal { public: Cat(void); ~Cat(void); void move(); private: int mice; };
— Cat.cpp —
#include "Cat.h" Cat::Cat(void) :Animal(4) // Call the superclass constructor to change the number of legs { this->mice = 12; } Cat::~Cat(void) { } void Cat::move() { Animal::move(); cout << "I ate "<<mice<<" Mice"<<endl; }
— utilities.h —
#ifndef UTILITIES_H #define UTILITIES_H #include <iostream> using namespace std; #endifBack to top