-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnamespacePolymorphism.cpp
64 lines (56 loc) · 1.43 KB
/
namespacePolymorphism.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
/*
* namespacePolymorphism.cpp
*/
#include <iostream>
using namespace std;
/*
? Namespace polymorphism means that,
? In namespaces with different type variables (int and float)
? it is possible to use the same function name;
! This is more commonly called "ad hoc polymorphism" or "inclusion polymorphism",
! because it is nothing more than an "overloading" of functions with namespace.
*/
/*
? in this example the two max functions use different types of variables,
? the call to the functions is "managed" automatically
*/
namespace calc {
void Max(int * a, int n, int & _max);
void Max(float * a, int n, float & _max);
};
// ? Max with integers
void calc::Max(int * a, int n, int & _max)
{
cout << "Computing Max of ints" << endl;
_max = a[0];
for (int i = 1; i < n;i++) {
if (a[i] > _max)
_max = a[i];
}
}
// ? Max with floating point numbers
void calc::Max(float * a, int n, float & _max)
{
cout << "Computing Max of floats" << endl;
_max = a[0];
for (int i = 1; i < n;i++) {
if (a[i] > _max)
_max = a[i];
}
}
int main(int argc, char * argv[])
{
cout << "Insert array size:";
int n;
cin >> n;
float * array = new float[n];
for (int i = 0; i < n;i++) {
cout << "Insert element "<< i << ":";
cin >> array[i];
}
float MAX;
calc::Max(array, n, MAX); // ? the call to the functions is "managed" automatically, int or float
cout << "Max is " << MAX << endl;
delete [] array;
return 0;
}