-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththrow.cpp
More file actions
96 lines (87 loc) · 2.32 KB
/
throw.cpp
File metadata and controls
96 lines (87 loc) · 2.32 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <memory>
#include <optional>
#include <stdexcept>
class Animal
{
private:
virtual void speak (void) = 0;
virtual void legs (void) = 0;
public:
void trigger_proxy(const std::unique_ptr<Animal> &ptr);
virtual ~Animal(void)
{
std::printf("Animal destroyed!!\n");
}
};
class Human : public Animal
{
public:
void speak(void) override;
void legs(void) override;
~Human(void)
{
std::printf("Human destroyed!!\n");
}
};
class Duck : public Animal
{
protected:
Duck(void)
{
throw std::runtime_error("hmm, looks like you aren't allowed to create this object!!\n");
}
public:
static std::optional<Duck *> Factory_func(void)
{
try {
return new Duck();
} catch (std::runtime_error &E) {
std::cerr << E.what();
}
return std::nullopt;
}
void speak(void) override;
void legs(void) override;
~Duck(void)
{
std::printf("Duck destroyed!!\n");
}
};
void Human::speak(void)
{
std::printf("Human speak speak!!\n");
}
void Human::legs(void)
{
std::printf("Humans are bipedal...\n");
}
void Duck::speak(void)
{
std::printf("Duck speak speak!!\n");
}
void Duck::legs(void)
{
std::printf("Ducks are bipedal...\n");
}
void Animal::trigger_proxy(const std::unique_ptr<Animal> &ptr)
{
ptr->speak();
ptr->legs();
std::printf("\n");
}
int main(void)
{
std::unique_ptr<Animal> ptr = nullptr;
ptr = std::make_unique<Human>();
ptr->trigger_proxy(ptr);
ptr = nullptr;
std::printf("\n");
const auto &factory_ptr = Duck::Factory_func();
if(factory_ptr.has_value())
{
ptr = std::unique_ptr<Duck>(factory_ptr.value());
ptr->trigger_proxy(ptr);
}
return 0;
}