-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path60-DynamicCast.cpp
More file actions
48 lines (39 loc) · 824 Bytes
/
60-DynamicCast.cpp
File metadata and controls
48 lines (39 loc) · 824 Bytes
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
//60-DynamicCast
#include <iostream>
class A{
public:
virtual void print(){
std::cout << "Hello from A." << std::endl;
}
};
class B: public A{
public:
void print() override{
std::cout << "Hello from B." << std::endl;
}
};
class C: public A{
public:
void print() override{
std::cout << "Hello from C." << std::endl;
}
};
//Base to Derived.
void Downcast(A* a){
auto p = dynamic_cast<B*>(a);
if(p){std::cout << "Downcast possible." << std::endl; p->print();}
else{std::cout << "Downcast not possible." << std::endl;}
}
//Derived to Base.
void Upcast(B* b){
auto p = dynamic_cast<A*>(b);
if(p){std::cout << "Upcast possible." << std::endl; p->print();}
else{std::cout << "Upcast not possible." << std::endl;}
}
int main(){
B* b = new B();
Downcast(b);
C* c = new C();
Downcast(c);
Upcast(b);
}