#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#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;
	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");
}
cs-142/animals.txt · Last modified: 2015/01/07 09:00 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