forked from learncppnow/9E
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13.Ex2.cpp
76 lines (63 loc) · 1.42 KB
/
13.Ex2.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
#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 crap" << endl;
}
};
void DetectFishType(Fish* InputFish)
{
Tuna* pIsTuna = dynamic_cast <Tuna*>(InputFish);
if (pIsTuna)
{
cout << "Detected Tuna. Making Tuna dinner: " << endl;
pIsTuna->BecomeDinner(); // calling Tuna::BecomeDinner
}
Carp* pIsCarp = dynamic_cast <Carp*>(InputFish);
if(pIsCarp)
{
cout << "Detected Carp. Making carp talk: " << endl;
pIsCarp->Talk(); // calling Carp::Talk
}
cout << "Verifying type using virtual Fish::Swim: " << endl;
InputFish->Swim(); // calling virtual function Swim
}
int main()
{
Fish* objFish = new Tuna;
Tuna* objTuna = static_cast<Tuna*>(objFish);
// Tuna::BecomeDinner will work only using valid Tuna*
objTuna->BecomeDinner();
// virtual destructor in Fish ensures invocation of ~Tuna()
delete objFish;
return 0;
}