-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvirtual_fn.cpp
More file actions
70 lines (57 loc) · 1.66 KB
/
Copy pathvirtual_fn.cpp
File metadata and controls
70 lines (57 loc) · 1.66 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
typedef uint32_t ui32;
typedef uint16_t ui16;
typedef uint8_t ui8;
constexpr ui8 AGE_REP = 2;
constexpr ui16 STEP = 0;
class Reptile {
protected:
ui8 its_age;
ui16 count_step;
public:
Reptile() : its_age(AGE_REP), count_step(STEP)
{
std::cout << "Reptile-constructor" << "\n";
}
virtual ~Reptile() {
std::cout << "Reptile-destructor" << "\n";
}
// Non-virtual, will call Reptile::move even from a Frog pointer.
void move(ui16 step) {
std::cout << "Reptile is moving.." << "\n";
count_step += step;
std::cout << "Steps: " << count_step << "\n";
}
// Use virtual allow make able Dynamic dispatch
virtual void speak(ui16 times = 0) const {
std::cout << "Reptile is speaking" << "\n" ;
}
};
class Frog : public Reptile {
public:
Frog() {
std::cout << "Frog-constructor" << "\n";
}
virtual ~Frog() {
std::cout << "Frog-destructor" << "\n";
}
void move(ui16 step) {
std::cout << "Frog is moving.." << "\n";
count_step += step;
std::cout << "Steps: " << count_step << "\n";
}
// Use "override" to ensure the signature matches with base class.
void speak(ui16 times) const override {
for (auto i = 0; i < times; ++i) {
std::cout << "Croack!" << "\n" ;
}
}
};
int main() {
Reptile* p_frog = new Frog;
p_frog->move(2);
p_frog->move(1);
p_frog->speak(3);
delete p_frog;
return 0;
}