#include <iostream>
#include <vector>
using namespace std;
class Cat;
class Dog;
class Animal;
typedef std::vector<Cat*> CatCollection;
typedef std::vector<Dog*> DogCollection;
typedef std::vector<Animal*> AnimalCollection;
class Animal {
public:
/* If the function is not virtual, then the child classes' functions
won't be called when calling from a variable of type Animal* */
virtual void doStuff() {
cout << "Animal stuff!" << endl;
}
};
class Cat : public Animal {
void doStuff() override {
cout << "Cat stuff!" << endl;
}
};
class Dog : public Animal {
void doStuff() override {
cout << "Dog stuff!" << endl;
}
};
int main() {
AnimalCollection coll;
//add elements
Cat *cat = new Cat();
Dog *dog = new Dog();
Animal *animal = new Animal();
coll.push_back(cat);
coll.push_back(animal);
coll.push_back(dog);
//do something with the first item of the collection
cout << "Checking the first item" << endl;
coll[0] -> doStuff();
cout << "Checking everything" << endl;
//do something on all items
for (Animal *c: coll) {
c -> doStuff();
}
//deleting memory as it was allocated with new
for (Animal *ptr: coll) {
delete ptr;
}
coll.clear(); //remove any reference to dangling pointers
return 0;
}