-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathvirtual.cpp
More file actions
38 lines (33 loc) · 851 Bytes
/
virtual.cpp
File metadata and controls
38 lines (33 loc) · 851 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <vector>
struct Animal {
const char* name;
Animal(const char* name) : name(name) {
}
virtual ~Animal() {
}
virtual void poke(std::ostream& os) = 0;
};
struct Dog : Animal {
using Animal::Animal;
void poke(std::ostream& os) override {
os << name << " barks.\n";
}
};
struct Cat : Animal {
using Animal::Animal;
void poke(std::ostream& os) override {
os << name << " hisses.\n";
}
};
void poke_animals(const std::vector<Animal*>& animals, std::ostream& os) {
for (auto animal : animals) {
animal->poke(os);
}
}
auto main() -> int {
Dog hector{"Hector"}, snoopy{"Snoopy"};
Cat felix{"Felix"}, sylvester{"Sylvester"};
std::vector<Animal*> animals = {&hector, &felix, &sylvester, &snoopy};
poke_animals(animals, std::cout);
}