-
Notifications
You must be signed in to change notification settings - Fork 2
/
type_casting.cpp
116 lines (95 loc) · 2.54 KB
/
type_casting.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <iostream>
struct Container {
std::string name;
Container(std::string name_arg) : name(name_arg){};
};
void implicit_cast() {
int a = 100;
long b = a;
std::cout << "a = " << a << ", b = " << b << "\n";
std::string s = "value";
Container c = s;
std::cout << "c.name = " << c.name << "\n";
};
class Parent {
std::string value = "parent";
public:
const std::string say() { return "I am parent (" + value + ")"; };
// virtual void hi(){};
};
class Child : public Parent {
// std::string value = "secret";
std::string value = "child";
public:
const std::string say() { return "I am child (" + value + ")"; };
};
void explicit_cast() {
int a = 100;
long b = (long)a;
std::cout << "a = " << a << ", b = " << b << "\n";
Child* c = new Child();
Parent* p = (Parent*)c;
std::cout << "p says " << p->say() << "\n";
std::cout << "c says " << c->say() << "\n";
delete c;
p = new Parent();
c = (Child*)p;
std::cout << "p says " << p->say() << "\n";
std::cout << "c says " << c->say() << "\n";
delete p;
}
void dynamic_cast_() {
Child* c = new Child();
Parent* p = dynamic_cast<Parent*>(c);
std::cout << "p says " << p->say() << "\n";
std::cout << "c says " << c->say() << "\n";
delete c;
// Only makes sense for polymorhic classes, i.e. with virtual methods
// p = new Parent();
// c = dynamic_cast<Child*>(p);
// if (c == nullptr) {
// std::cout << "nullptr\n";
// return;
// }
// std::cout << "p says " << p->say() << "\n";
// std::cout << "c says " << c->say() << "\n";
// delete p;
}
void static_cast_() {
Child* c = new Child();
Parent* p = static_cast<Parent*>(c);
std::cout << "p says " << p->say() << "\n";
std::cout << "c says " << c->say() << "\n";
delete c;
p = new Parent();
c = static_cast<Child*>(p);
if (c == nullptr) {
std::cout << "nullptr\n";
return;
}
std::cout << "p says " << p->say() << "\n";
std::cout << "c says " << c->say() << "\n";
delete p;
}
void reinterpret_cast_() {
Child* c = new Child();
// with static_cast you'll get error: invalid 'static_cast' from type 'Child*'
// to type 'const char*'
const char* p = reinterpret_cast<const char*>(c);
std::cout << "p text " << p << "\n";
delete c;
}
void const_cast_() {
const Child* c = new Child();
Child* c2 = const_cast<Child*>(c);
std::cout << "c says " << c2->say() << "\n";
delete c;
}
int main() {
implicit_cast();
// explicit_cast();
// dynamic_cast_();
// static_cast_();
// reinterpret_cast_();
// const_cast_();
}