-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCDestructors.cpp
More file actions
73 lines (59 loc) · 1.92 KB
/
CDestructors.cpp
File metadata and controls
73 lines (59 loc) · 1.92 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
#include <iostream>
using namespace std;
// ** 1. Basic Destructor**
// - Generated if no destructor is declared
// - Calls destructors of members automatically
// - Does not free dynamically allocated memory unless you write it
namespace Basic {
class CDestructors {
public:
CDestructors() { cout << "Called CDestructors() \n"; }
~CDestructors() { cout << "Called ~CDestructors() \n"; }
// Using `default` keyword
// ~CDestructors() = default;
// Using `delete` // I forbid this destructor
// ~CDestructors() = delete;
};
void destructers() {
cout << "\n--- Basic Destructer Examples ---\n";
{ CDestructors obj; }
}
} // namespace Basic
// **2. Virtual Destructor**
namespace Virtual {
class CDestructorsBase // final => cannot inherit
{
public:
CDestructorsBase() { cout << "Called CDestructorsBase() \n"; }
virtual ~CDestructorsBase() { cout << "Called ~CDestructorsBase() \n"; }
// Using `default` keyword
// ~CDestructorsBase() = default;
};
class CDestructorsDerived : public CDestructorsBase {
public:
CDestructorsDerived() { cout << "Called CDestructorsDerived() \n"; }
~CDestructorsDerived() override {
cout << "Called ~CDestructorsDerived() \n";
}
};
void destructers() {
cout << "\n--- Virtual Destructer Examples ---\n";
CDestructorsDerived* derived = {new CDestructorsDerived()};
CDestructorsBase* base{derived};
delete base;
// without virtual -> only call ~CDestructorsBase()
// with virtual -> call ~CDestructorsBase() && ~CDestructorsDerived()
}
} // namespace Virtual
#include "ExampleRegistry.h"
class CDestructors : public IExample {
public:
std::string group() const override { return "core/class"; }
std::string name() const override { return "CDestructors"; }
std::string description() const override { return ""; }
void execute() override {
Basic::destructers();
Virtual::destructers();
}
};
REGISTER_EXAMPLE(CDestructors, "core/class", "CDestructors");