-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCastings.cpp
More file actions
103 lines (86 loc) · 2.49 KB
/
Copy pathCastings.cpp
File metadata and controls
103 lines (86 loc) · 2.49 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
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
/**
* Demonstrate casting using
* - static_cast<> -> do a compile-time based casting to the target
* - dynamic_cast<> -> rely on run-time check whether such type can be casted to the target
* - reinterpret_cast<> -> rawly interpret from one type to another without modification
* - const_cast<> -> to cast away const ness (only this operator can do it)
*
* When compiled, you will see compile error as following
*
* Castings.cpp:38:7: warning: direct base ‘A’ inaccessible in ‘Derived’ due to ambiguity
* class Derived : public A, public B
*
* don't worry about the error above as we intend to do multiple inhiritance here for studying purpose.
*
* Line comments uses #if 0 and #endif pair for clearer to see in code. Change 0 to 1 to enable such
* code section.
*/
#include <iostream>
struct Widget
{
int a;
Widget() : a(0) {}
Widget(int a) : a(a) {}
};
struct NotRelatedWidget
{
int a;
};
// -- for testing casting --
class A
{
int a;
};
class B : public A
{
int b;
};
class Derived : public A, public B
{
int d;
};
// -- end section --
int main()
{
Widget a;
const Widget b(1);
const Widget* ptr = &b;
// this is fine
static_cast<const Widget>(a);
// this line is compile error, cannot modify const object
#if 0
static_cast<const Widget>(a).a = 10;
#endif
// although no error, but static_cast<> cannot cast constness away
// if uncomment this line, then compile error occurs
#if 0
static_cast<Widget>(b).a = 10;
#endif
// these three lines cast away constness. CANNOT DO IT!
// result in compile error
#if 0
static_cast<Widget*>(ptr);
reinterpret_cast<Widget*>(ptr);
dynamic_cast<Widget*>(ptr);
#endif
// to cast away constness, use const_cast
Widget* cPtr = const_cast<Widget*>(ptr);
cPtr->a = 20;
std::cout << "cPtr->a = " << cPtr->a << std::endl;
// casting to un-related type won't be allowed, compiler error here
// as static_cast is based on compile-time for this line (anyway it can be runtime in case it really needs)
// note: uncomment this then compile to see the effect
#if 0
static_cast<NotRelatedWidget>(a);
#endif
// testing down-cast from base to derived class
Derived* dPtr = new Derived();
#if 0
// ambiguous, not OK
static_cast<A*>(dPtr);
dynamic_cast<A*>(dPtr);
#endif
// this is fine, we know what we're doing
reinterpret_cast<A*>(dPtr);
return 0;
}