To download the code, click here
01: #include <iostream>
02: #include <string>
03:
04: #include <cmath>
05:
06: //examples of function overloading
07: int max(int a, int b){
08: return a > b ? a : b;
09: }
10:
11: int max(int a, int b, int c){
12: int d = max(b,c);
13: return a > d ? a : d;
14: }
15:
16: //this function definition
17: float max(float a, float b){
18: return a > b ? a : b;
19: }
20:
21: //and this one, result in the following error:
22: /*
23: 12march.cpp:20: error: new declaration 'double max(float, float)'
24: 12march.cpp:16: error: ambiguates old declaration 'float max(float, float)'
25: */
26: //double max(float a, float b){
27: // return a > b ? a : b;
28: //}
29:
30:
31: /*
32: take note of the default paramter
33:
34: this default parameter can be excluded from the function call, so in a sense,
35: the below defines 2 different function calls. If there were more default
36: parameters, you would have to specify them IN ORDER when you call the function.
37:
38: Later defaults cannot be specified without specifying earlier default values.
39: */
40: void print_numbers(int a, int b, std::ostream &outs = std::cout){
41:
42: outs << a << "\t" << b << std::endl;
43:
44: return;
45: }
46:
47:
48:
49:
50: int main(int argc, char *argv[]){
51:
52: int a = 11;
53: int b = 5;
54:
55: //type cast example
56: double d = static_cast<double>(a) / b;
57:
58: max(1,2,3);
59: max(1,2);
60: max(1,2,max(3,4));
61:
62: print_numbers(2, 3, std::cerr);
63:
64: //must be explicitly floating point values, otherwise abiguity error
65: double four = std::pow(2.0, 2.0);
66:
67: return 0;
68: }
69: