-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanimal.cpp
More file actions
44 lines (35 loc) · 948 Bytes
/
animal.cpp
File metadata and controls
44 lines (35 loc) · 948 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
39
40
41
42
43
#include <iostream>
#include <memory>
// 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;
}
};
void whatDoesTheAnimalSay(const Animal& a) {
a.speak();
}
// main function
int main() {
std::unique_ptr<Animal> dog = std::make_unique<Dog>();
std::unique_ptr<Animal> cat = std::make_unique<Cat>();
whatDoesTheAnimalSay(*dog); // outputs: bark
whatDoesTheAnimalSay(*cat); // outputs: meow
std::cout << "Sizeof(Dog) is " << sizeof(Dog) << std::endl;
std::cout << "Sizeof(void*) is " << sizeof(void*) << std::endl;
return 0;
}