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;
#endif
cs-142/inheritance2.txt · Last modified: 2014/11/13 09:27 by kseppi
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0