+ 1

what is function overloading? plzz help I don't understand...

22nd Jul 2016, 2:52 PM
krishna desai
9 Antworten
+ 3
#include<iostream> using namespace std; int sum(int, int); int sum(int, int, int); int main() { int a, b, c, choice; char stop[20]; cout << "\na: "; cin >> a; cout << "\nb: "; cin >> b; cout << "\nc: "; cin >> c; do { cout << "\n\nif you want to sum a+b press 1+ENTER\nif you want to sum a+b+c press 2+ENTER\n------------------\nyour choice: "; cin >> choice; } while (choice != 1 && choice != 2); cout << "\n\n\n"; switch (choice) { case 1: sum(a, b); break; case 2: sum(a, b, c); break; } cout << "\n\n\nPress a letter/number+ENTER to exit "; cin >> stop; return 0; } int sum(int x, int y) { int tot = x + y; cout << "x + y = " << tot; return tot; } int sum(int x, int y, int z) { int tot = x + y + z; cout << "x + y + z = " << tot; return tot; }
22nd Jul 2016, 4:24 PM
Phumus-9
Phumus-9 - avatar
0
you can create 2 functions with the same name and return type, but with different arguments. So, when u call that function, the compiler use the most appropriate, according on what argument(s) u pass to the function. If u want I can write an example ;) Bye!
22nd Jul 2016, 3:08 PM
Phumus-9
Phumus-9 - avatar
0
yes plzz!! :)
22nd Jul 2016, 3:23 PM
krishna desai
0
thanks:)
22nd Jul 2016, 4:32 PM
krishna desai
0
IMPORTANT: I recommend u to run the code I posted on a PC and not on "code playground", if u can, because there are several inputs. As u can see, there are 2 functions called "sum", but the first function requires 2 int values ( sum (int x, int y)), whereas the second one require 3 int values (sum (int x, int y, int z)). So, when I call the function sum, and I pass it 2 int variables (a and b), the compiler uses the first function, whereas if I pass it 3 values (a, b and c), the compiler uses the second one.
22nd Jul 2016, 4:33 PM
Phumus-9
Phumus-9 - avatar
0
U can do the same thing when u create 2 functions with the same number of arguments but with different data types. For example "sum (float, int)" and "sum (int, double)". U can overload as many functions as u want. For example "sum (int, int)", "sum (int, int, int", "sum (float, int, float)", ...
22nd Jul 2016, 4:39 PM
Phumus-9
Phumus-9 - avatar
0
okay!!**
22nd Jul 2016, 4:39 PM
krishna desai
0
you are welcome :) if u don't understand something just tell me!
22nd Jul 2016, 4:40 PM
Phumus-9
Phumus-9 - avatar
0
thanks for your kindly support:) tomorrow I will try this program in my PC and if any doubt I just tell.....
22nd Jul 2016, 4:45 PM
krishna desai