After creating the vector, the Animal and Fish references will be accessed and the respire() method executed on each instance using the new for loop and then the STL for_each method.
#include <iostream>
#include <vector>
using namespace std;
class Animal {
public:
virtual string respire() = 0;
};
class Mammal:public Animal {
public:
string respire() {
return "huff, puff";
}
};
class Fish: public Animal {
public:
string respire() {
return "bubbles";
}
};
int main() {
Mammal dog, cat;
Fish goldfish;
vector<Animal *> animals = {&cat, &dog, &goldfish};
for (auto a : animals) {
cout << a->respire() << endl;
}
for_each(
animals.begin(),
animals.end(),
[](Animal* x){cout << x->respire() << endl;});
}
$ g++ -std=c++14 -c -o Animals.o Animals.cpp $ g++ -o Animals Animals.o $ ./Animals huff, puff huff, puff bubbles huff, puff huff, puff bubbles $