-
Notifications
You must be signed in to change notification settings - Fork 23
/
11.9 VirtualCopyConstructors.cpp
75 lines (63 loc) · 1.32 KB
/
11.9 VirtualCopyConstructors.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
#include <iostream>
using namespace std;
class Fish
{
public:
virtual Fish* Clone() = 0;
virtual void Swim() = 0;
virtual ~Fish() {};
};
class Tuna: public Fish
{
public:
Fish* Clone() override
{
return new Tuna (*this);
}
void Swim() override final
{
cout << "Tuna swims fast in the sea" << endl;
}
};
class BluefinTuna final:public Tuna
{
public:
Fish* Clone() override
{
return new BluefinTuna(*this);
}
// Cannot override Tuna::Swim as it is "final" in Tuna
};
class Carp final: public Fish
{
Fish* Clone() override
{
return new Carp(*this);
}
void Swim() override final
{
cout << "Carp swims slow in the lake" << endl;
}
};
int main()
{
const int ARRAY_SIZE = 4;
Fish* myFishes[ARRAY_SIZE];
myFishes[0] = new Tuna();
myFishes[1] = new Carp();
myFishes[2] = new BluefinTuna();
myFishes[3] = new Carp();
Fish* myNewFishes[ARRAY_SIZE];
for (int index = 0; index < ARRAY_SIZE; ++index)
myNewFishes[index] = myFishes[index]->Clone();
// invoke a virtual method to check
for (int index = 0; index < ARRAY_SIZE; ++index)
myNewFishes[index]->Swim();
// memory cleanup
for (int index = 0; index < ARRAY_SIZE; ++index)
{
delete myFishes[index];
delete myNewFishes[index];
}
return 0;
}