-
Notifications
You must be signed in to change notification settings - Fork 549
/
Copy path13_04.cpp
52 lines (38 loc) · 990 Bytes
/
13_04.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
#include <bits/stdc++.h>
using namespace std;
class A { // must be virtual to cast
public:
virtual ~A() { }
};
class B: public A {};
class C: public A {};
class D {};
void dynamic_cast_test() {
// Run time conversion using RTTI
A* a_from_b = new B();
// No problem. Valid conversion
B* b = dynamic_cast<B*>(a_from_b);
cout<<b<<"\n";
// Wrong conversion, pointer = nullptr
C* c = dynamic_cast<C*>(a_from_b);
cout<<c<<"\n";
// Wrong conversion, pointer = nullptr
D* d = dynamic_cast<D*>(a_from_b);
cout<<d<<"\n";
}
void static_cast_test() {
// Compile time check/cast
A* a_from_b = new B();
// No problem. Valid conversion
B* b = static_cast<B*>(a_from_b);
cout<<b<<"\n";
// Wrong conversion, but u get pointer :(
C* c = static_cast<C*>(a_from_b);
cout<<c<<"\n";
// Compilation error can be caught for such clear case
//D* d = static_cast<D*>(a_from_b);
}
int main() {
dynamic_cast_test();
return 0;
}