-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanimal-template.cpp
More file actions
55 lines (45 loc) · 1.18 KB
/
animal-template.cpp
File metadata and controls
55 lines (45 loc) · 1.18 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
// Base class
class Animal {
public:
virtual void speak() const = 0; // pure virtual function
virtual ~Animal() = default; // a destructor is required
};
// Subclass: Dog
class Dog : public Animal {
public:
void speak() const override {
std::cout << "bark" << std::endl;
}
};
// Subclass: Cat
class Cat : public Animal {
public:
void speak() const override {
std::cout << "meow" << std::endl;
}
};
class Elephant : public Animal {
public:
void speak() const override {
std::cout << "I'm gonna crush you!" << std::endl;
}
};
template<typename T>
void whatDoesTheAnimalSay(const T& a) {
static_assert(std::is_base_of<Animal, T>::value, "T must inherit from Animal");
a.speak();
}
// main function
int main() {
Dog dog;
Cat cat;
Elephant elephant;
whatDoesTheAnimalSay(dog); // outputs: bark
whatDoesTheAnimalSay(cat); // outputs: meow
whatDoesTheAnimalSay(elephant);
std::cout << "Sizeof(Dog) is " << sizeof(Dog) << std::endl;
std::cout << "Sizeof(void*) is " << sizeof(void*) << std::endl;
std::cout << "Sizeof(Elephant) is " << sizeof(Elephant) << std::endl;
return 0;
}