-
Notifications
You must be signed in to change notification settings - Fork 23
/
13.1 dynamic_cast_Fish.cpp
74 lines (62 loc) · 1.27 KB
/
13.1 dynamic_cast_Fish.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
#include <iostream>
using namespace std;
class Fish
{
public:
virtual void Swim()
{
cout << "Fish swims in water" << endl;
}
// base class should always have virtual destructor
virtual ~Fish() {}
};
class Tuna: public Fish
{
public:
void Swim()
{
cout << "Tuna swims real fast in the sea" << endl;
}
void BecomeDinner()
{
cout << "Tuna became dinner in Sushi" << endl;
}
};
class Carp: public Fish
{
public:
void Swim()
{
cout << "Carp swims real slow in the lake" << endl;
}
void Talk()
{
cout << "Carp talked carp!" << endl;
}
};
void DetectFishType(Fish* objFish)
{
Tuna* objTuna = dynamic_cast <Tuna*>(objFish);
if (objTuna)
{
cout << "Detected Tuna. Making Tuna dinner: " << endl;
objTuna->BecomeDinner(); // calling Tuna::BecomeDinner
}
Carp* objCarp = dynamic_cast <Carp*>(objFish);
if(objCarp)
{
cout << "Detected Carp. Making carp talk: " << endl;
objCarp->Talk(); // calling Carp::Talk
}
cout << "Verifying type using virtual Fish::Swim()" << endl;
objFish->Swim(); // calling virtual function Swim
}
int main()
{
Carp myLunch;
Tuna myDinner;
DetectFishType(&myDinner);
cout << endl;
DetectFishType(&myLunch);
return 0;
}