-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic_cast.cpp
60 lines (49 loc) · 1.25 KB
/
dynamic_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
#include <iostream>
#include <typeinfo>
using std::cout;
using std::endl;
class Base {
public:
Base()
{}
virtual ~Base()
{}
protected:
virtual void dummy()
{}
};
class Derived : public Base {};
int main()
{
{
Base* b1 = new Derived;
Base* b2 = new Base;
Derived* d1 = dynamic_cast<Derived*>(b1);
if (d1)
cout << "Derived* d1 = dynamic_cast<Derived*>(b1) successfull" << endl;
else
cout << "Derived* d1 = dynamic_cast<Derived*>(b1) unsuccessfull" << endl;
Derived* d2 = dynamic_cast<Derived*>(b2);
if (d2)
cout << "Derived* d2 = dynamic_cast<Derived*>(b2) successfull" << endl;
else
cout << "Derived* d2 = dynamic_cast<Derived*>(b2) unsuccessfull" << endl;
}
{
try {
Base* b1 = new Derived;
Base* b2 = new Base;
Derived& d1 = dynamic_cast<Derived&>(*b1);
std::cout << "dynamic_cast used to convert b1=" << b1
<< " into d1=" << &d1 << std::endl;
Derived& d2 = dynamic_cast<Derived&>(*b2);
std::cout << "dynamic_cast used to convert b2=" << b2
<< " into d2=" << &d2 << std::endl;
return 0;
}
catch (std::bad_cast& x) {
std::cerr << "dynamic_cast failed: " << x.what() << endl;
return 0;
}
}
}