forked from parallel101/course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc.cpp
62 lines (46 loc) · 1.31 KB
/
c.cpp
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
#include <memory>
#include <string>
#include <iostream>
using namespace std;
struct IObject {
IObject() = default;
IObject(IObject const &) = default;
IObject &operator=(IObject const &) = default;
virtual ~IObject() = default;
virtual void eatFood() = 0;
virtual shared_ptr<IObject> clone() const = 0;
};
#define IOBJECT_DEFINE_CLONE \
virtual shared_ptr<IObject> clone() const override { \
return make_shared<decay_t<decltype(*this)>>(*this); \
}
struct CatObject : IObject {
string m_catFood = "someFish";
IOBJECT_DEFINE_CLONE
virtual void eatFood() override {
cout << "eating " << m_catFood << endl;
m_catFood = "fishBones";
}
virtual ~CatObject() override = default;
};
struct DogObject : IObject {
string m_dogFood = "someMeat";
IOBJECT_DEFINE_CLONE
virtual void eatFood() override {
cout << "eating " << m_dogFood << endl;
m_dogFood = "meatBones";
}
virtual ~DogObject() override = default;
};
void eatTwice(IObject *obj) {
shared_ptr<IObject> newObj = obj->clone();
obj->eatFood();
newObj->eatFood();
}
int main() {
shared_ptr<CatObject> cat = make_shared<CatObject>();
shared_ptr<DogObject> dog = make_shared<DogObject>();
eatTwice(cat.get());
eatTwice(dog.get());
return 0;
}