#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <stdlib.h>
using namespace std;
class Animal {
public:
virtual void eat() = 0;
};
// Dog is more high-level
class Dog: public Animal {
public:
char attr1;
char attr2;
Dog(char _attr1, char _attr2):
attr1(_attr1),
attr2(_attr2)
{}
Dog():
attr1('d'),
attr2('g')
{}
void eat() {
cout << "Dog ate food (" << attr1 << attr2 << ").\n";
}
void barf() {
cout << "Whaf";
}
};
// Cat is more low-level
class Cat: public Animal {
public:
// A cat can basically only exist in a cage
// and it's attributes are defined by it's location
// in the Cage's underlying array. A Cat should also
// have to 2 attributes (both char), so this would
// be kind of true:
// sizeof(Cat) == 2
char* ptr;
// I will only use a Cat in a context of arrays, so
// no need to care about memory management here.
Cat(char* _ptr):
ptr(_ptr)
{}
void eat() {
cout << "Cat ate food (" << *ptr << *(ptr+1) << ").\n";
}
void meow() {
cout << "Meow.";
}
};
class Cage {
public:
virtual Animal* GetRandomAnimal() = 0;
};
// DogCage uses a nice (more high level) vector
class DogCage: public Cage {
public:
vector<Dog> dogs;
DogCage():
dogs(5)
{
dogs[0] = Dog();
}
Animal* GetRandomAnimal() {
return &dogs[0];
}
};
// CatCage uses a more low level pointer together with
// malloc etc.
class CatCage: public Cage {
public:
char* cats;
CatCage():
cats((char*) malloc(4*2)) // room for 4 cats
{
*cats = 'c';
*(cats+1) = 't';
}
~CatCage() {
free(cats);
}
Animal* GetRandomAnimal() {
int random = 0;
// This is why it's difficult to return a pointer
// to an Animal. I basically want to use a Cat as
// a simple interface to a part of an array.
// If I use pointers etc, that seems like it would
// hit performance.
Cat* c = new Cat(cats+(random*2));
return c;
}
};
void FeedAnimals(Animal& a) {
a.eat();
}
int main() {
//Cage cage;
string s;
cout << "Cats or dogs? ";
cin >> s;
if (s=="Cats" || s=="cats" || s=="c") {
CatCage cage = CatCage();
FeedAnimals(*(cage.GetRandomAnimal()));
} else {
DogCage cage = DogCage();
FeedAnimals(*(cage.GetRandomAnimal()));
}
}