fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class Cat;
  6. class Dog;
  7. class Animal;
  8.  
  9. typedef std::vector<Cat*> CatCollection;
  10. typedef std::vector<Dog*> DogCollection;
  11. typedef std::vector<Animal*> AnimalCollection;
  12.  
  13. class Animal {
  14. public:
  15. /* If the function is not virtual, then the child classes' functions
  16.   won't be called when calling from a variable of type Animal* */
  17. virtual void doStuff() {
  18. cout << "Animal stuff!" << endl;
  19. }
  20. };
  21.  
  22. class Cat : public Animal {
  23. void doStuff() override {
  24. cout << "Cat stuff!" << endl;
  25. }
  26. };
  27.  
  28. class Dog : public Animal {
  29. void doStuff() override {
  30. cout << "Dog stuff!" << endl;
  31. }
  32. };
  33.  
  34. int main() {
  35. AnimalCollection coll;
  36.  
  37. //add elements
  38. Cat *cat = new Cat();
  39. Dog *dog = new Dog();
  40. Animal *animal = new Animal();
  41.  
  42. coll.push_back(cat);
  43. coll.push_back(animal);
  44. coll.push_back(dog);
  45.  
  46. //do something with the first item of the collection
  47. cout << "Checking the first item" << endl;
  48. coll[0] -> doStuff();
  49.  
  50. cout << "Checking everything" << endl;
  51. //do something on all items
  52. for (Animal *c: coll) {
  53. c -> doStuff();
  54. }
  55.  
  56. //deleting memory as it was allocated with new
  57. for (Animal *ptr: coll) {
  58. delete ptr;
  59. }
  60. coll.clear(); //remove any reference to dangling pointers
  61.  
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
Checking the first item
Cat stuff!
Checking everything
Cat stuff!
Animal stuff!
Dog stuff!