-
Notifications
You must be signed in to change notification settings - Fork 22
/
Type_Casting_Operators_III(static_cast).cpp
90 lines (72 loc) · 2.24 KB
/
Type_Casting_Operators_III(static_cast).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
#include<iostream>
using namespace std;
/*
static cast : As the name signifies, it deals with casting which can be decided at compile time.
It performs all conversions allowed implicitly.
void* -> any pointer type
I also up-casts and down-casts (at risk) as well
*/
int main() {
//Built-in types
int i = 2;
double d = 3.7;
double *pd = &d;
i = d; //implicit -- warning
i = static_cast<int>(d); //static_cast -- okay
i = (int)d; //C-style -- okay
d = i; //implicit -- okay
d = static_cast<double>(i); //implicit -- okay
d = (double)i; //implicit -- okay
//i = pd; //implicit -- Error
//i = static_cast<int>(pd); //static_cast -- Error
//i = (int)pd; //C-style -- okay (Risky) (Also error with latest C++)
return 0;
}
class A { };
class B : public A { };
int main() {
A a;
B b;
//UPCAST
A *p = &b; //implicit -- okay
p = static_cast<A*>(&b); //static_cast -- okay
p = (A*)&b; //C-style -- okay
//DOWNCAST
//B *q = &a; //implicit -- Error
q = static_cast<B*>(&a); //static_cast -- okay (Risky)
q = (B*)&a; //C-style -- okay
return 0;
}
//conversion operator
class B;
class A {
int i_;
public:
A(int i = 0) : i_(i) {}
//conversion operator : Means, you want to convert A to an int type
operator int() {
//just like operator +()
//No return type because it's obvious
return i_;
}
};
class B {
public:
//conversion operator : Means, you want to convert B to an A type
operator A() {
return A();
}
};
int main() {
A a;
B b;
int i = 5;
//B --> A (Note, A and B are unrelated classes)
a = b; //B::operator A()
a = static_cast<A>(b); //B::operator A()
a = (A)b; //B::operator A()
//A --> int (strange haan. Why would anyone do this :-|)
i = a; //A::operator int()
i = static_cast<int>(a);//A::operator int()
i = (int)a; //A::operator int()
}