**This is an old revision of the document!**

<code cpp >

  1. include <iostream>
  2. include <fstream>
  3. include <vector>
  4. include <sstream>
  5. include <string>

using namespace std; class Animal { public:

virtual void do_act() const;

}; void Animal::do_act() const { cout «“Move Move!”«endl; };

class Dog : public Animal { public:

virtual void do_act() const;

}; void Dog::do_act() const { cout «“Bark Bark!”«endl; };

class Cat : public Animal { public:

Cat() {mouse = 4;};
virtual void do_act() const;
int mouse;

}; void Cat::do_act() const { cout «“Scratch Scratch! ”«mouse«endl; };

int main() {

vector<Animal *> animals;
Dog fido;
Cat fritz;
Animal snail;
cout << "The dog "<<endl;
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[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[1].do_act(); // This will call the Animal do_act

} </code >

cs-142/animals.1420646384.txt.gz · Last modified: 2015/01/07 15:59 by ryancha
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