-
Notifications
You must be signed in to change notification settings - Fork 0
/
virtual-and-smart-destructor.cpp
76 lines (67 loc) · 1.29 KB
/
virtual-and-smart-destructor.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <new>
#include <memory>
#include <atomic>
#include <thread>
#include <mutex>
#include <future>
#include <utility>
#include <tuple>
#include <string>
#include <array>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <algorithm>
#include <iterator>
#include <functional>
#include <regex>
#include <bitset>
#include <iostream>
using namespace std;
// using virtual destructors in polymorphic base classes
// Note: all classes in STL have no virtual destructor, inherit from them carefully
class Dog
{
public:
virtual ~Dog()
{
cout << "Dog destroyed" << endl;
}
virtual void bark() {}
};
class YellowDog : public Dog
{
public:
~YellowDog()
{
cout << "YellowDog destroyed" << endl;
}
};
class DogFactory
{
public:
static shared_ptr<Dog> createYellowDog()
{
// ...
return shared_ptr<YellowDog>(new YellowDog());
}
};
int main()
{
// Dog *pd = DogFactory::createYellowDog();
// delete pd;
// with shared pointer no need to delete
// virtual destructor can also be removed
shared_ptr<Dog> pd = DogFactory::createYellowDog();
// destructors called:
// - YellowDog destroyed
// - Dog destroyed
return 0;
}