Differences

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

Link to this comparison view

cs-142:inheritance [2014/11/11 15:20] (current)
kseppi created
Line 1: Line 1:
 +<code c++> 
 +#include <​iostream>​ 
 +#include <​fstream>​ 
 +#include <​vector>​ 
 +#include <​sstream>​ 
 +#include <​string>​ 
 +  
 +using namespace std; 
 +  
 +class Animal 
 +
 +public: 
 + virtual void do_act(); 
 +}; 
 +void Animal::​do_act() { cout <<"​Move Move!"<<​endl;​ }; 
 +  
 +class Dog : public Animal { 
 +public: 
 + virtual void do_act(); 
 +}; 
 +void Dog::​do_act() { cout <<"​Bark Bark!"<<​endl;​ }; 
 +  
 +class Cat : public Animal { 
 +public: 
 + Cat() {mouse = 4;}; 
 + virtual void do_act(); 
 + int mouse; 
 +}; 
 +void Cat::​do_act() { cout <<"​Scratch Scratch! "<<​mouse<<​endl;​ }; 
 +  
 +int main() { 
 + vector<​Animal *> animals; 
 + Dog fido; 
 + Cat fritz; 
 + Animal snail; 
 +  
 + cout << "The dog "<<​endl;​ 
 + fido.do_act();​ 
 +  
 + cout <<"​The cat through an Animal Pointer"<<​endl;​ 
 + Animal *aptr = &​fritz;​ 
 + aptr->​do_act();​ // Since we used the pointer, we still have the Cat behavior 
 +  
 + cout <<"​The cat assigned to an Animal"<<​endl;​ 
 + snail = fritz; 
 + snail.do_act();​ // Slicing stripped off the cat behavior and data 
 +  
 + cout <<"​The cat in a vector of Animal pointers"<<​endl;​ 
 + animals.push_back(&​fido);​ 
 + animals.push_back(&​fritz);​ 
 + animals[1]->​do_act();​ // Since we didnt copy, we can still call the Cat do_act 
 +  
 + cout <<"​The cat in a vector of Animals"<<​endl;​ 
 + vector<​Animal > pets; 
 + pets.push_back(fido);​ 
 + pets.push_back(fritz);​ 
 + pets[1].do_act();​ // This will call the Animal do_act 
 +  
 +  
 + system("​pause"​);​ 
 +
 +</​code>​
cs-142/inheritance.txt · Last modified: 2014/11/11 15:20 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