-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path211206_polymorphism1.cpp
More file actions
100 lines (85 loc) · 1.69 KB
/
211206_polymorphism1.cpp
File metadata and controls
100 lines (85 loc) · 1.69 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
#include <cstdio>
class Base
{
public:
Base() = default;
const char* name = "Base";
Base(const Base& rhs) { puts("Base copy const."); }
};
class Derived : public Base
{
public:
Derived() = default;
const char* name = "Derived";
};
void f1(Base b)
{
puts(b.name);
}
void f2(Base& rb)
{
puts(rb.name);
puts(static_cast<Derived&>(rb).name);
}
void f3(const Base& crb)
{
puts(crb.name);
puts(static_cast<const Derived&>(crb).name);
}
void f4(Base* pb)
{
puts(pb->name);
puts(static_cast<Derived*>(pb)->name);
// compiler error: cannot 'dynamic_cast' 'pb' (of type 'class Base*') to type 'class Derived*' (source type is not polymorphic)
// puts(dynamic_cast<Derived*>(pb)->name);
// ^~~~~~~~~~~~~~~~~~~~~~~~~~
// add virtual destructor to Base then it compiles
}
void f5(Base* const cpb)
{
puts(cpb->name);
puts(static_cast<Derived* const>(cpb)->name);
puts(static_cast<Derived*>(cpb)->name); // OK
}
void f6(const Base* pcb)
{
puts(pcb->name);
puts(static_cast<const Derived*>(pcb)->name);
// compiler error: 'static_cast' from type 'const Base*' to type 'Derived*' casts away quialifiers
// puts(static_cast<Derived*>(pcb)->name); // NOT OK
//
}
void f7(const Base* const cpcb)
{
puts(cpcb->name);
puts(static_cast<const Derived*>(cpcb)->name); // OK
puts(static_cast<const Derived* const>(cpcb)->name); // OK
}
int main()
{
Derived d;
f1(d);
f2(d);
f3(d);
f4(&d);
f5(&d);
f6(&d);
f7(&d);
}
// Output:
// Base copy const.
// Base
// Base
// Derived
// Base
// Derived
// Base
// Derived
// Base
// Derived
// Derived
// Base
// Derived
// Base
// Derived
// Derived