The term function overloading refers to the way C++ allows more than one function in the same scope to share the same name -- as long as they have different parameter lists
int Process(double num); // function 1 int Process(char letter); // function 2 int Process(double num, int position); // function 3
int x; float y = 12.34; x = Process(3.45, 12); // invokes function 3 x = Process('f'); // invokes function 2 x = Process(y); // invokes function 1 (automatic type conversion applies)
void DoTask(int x, double y); void DoTask(double a, int b);
DoTask(4, 5.9); // calls function 1 DoTask(10.4, 3); // calls function 2 DoTask(1, 2); // ambiguous due to type conversion (int -> double)
int Compute(int x, int y, int z = 5); // z has a default value void RunAround(char x, int r = 7, double f = 0.5); // r and f have default valuesLegal Calls
int a = 2, b = 4, c = 10, r; cout << Compute(a, b, c); // all 3 parameters used (2, 4, 10) r = Compute(b, 3); // z takes its default value of 5 // (only 2 arguments passed in) RunAround('a', 4, 6.5); // all 3 arguments sent RunAround('a', 4); // 2 arguments sent, f takes default value RunAround('a'); // 1 argument sent, r and f take defaults
void Jump(int a, int b = 2, int c); // This is illegal
int Process(double num); // function 1 int Process(char letter); // function 2 int Process(double num, int position); // function 3Now suppose we declare the following function:
int Process(double x, int y = 5); // function 4This function conflicts with function 3, obviously. It ALSO conflicts with function 1. Consider these calls:
cout << Process(12.3, 10); // matches functions 3 and 4 cout << Process(13.5); // matches functions 1 and 4So, function 4 cannot exist along with function 1 or function 3
BE CAREFUL to take default parameters into account when using
function overloading!