#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");
}
Back to top