Differences

This shows you the differences between two versions of the page.

Link to this comparison view

cs-142:inheritance2 [2014/11/13 16:27] (current)
kseppi created
Line 1: Line 1:
 +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 ---
 +<code c++>
 +#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"​);​
 +}
 +
 +</​code>​
 +
 +---  Animal.h ---
 +<code cpp>
 +#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
 +</​code>​
 +--- Animal.cpp ---
 +<code 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;
 +}
 +</​code>​
 +--- Cat.h ---
 +<code c++>
 +#pragma once
 +#include "​Animal.h"​
 +class Cat :
 + public Animal
 +{
 +public:
 + Cat(void);
 + ~Cat(void);​
 + void move();
 +private:
 + int mice;
 +};
 +</​code>​
 +--- Cat.cpp ---
 +<code 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;​
 +}
 +</​code>​
 +--- utilities.h ---
 +<code c++>
 +#ifndef UTILITIES_H
 +#define UTILITIES_H
 +#include <​iostream>​
 +using namespace std;
 +#endif
 +</​code>​
cs-142/inheritance2.txt ยท Last modified: 2014/11/13 16: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