TOPIC: FUNCTION OVERLOADING
FUNCTION OVERLOADING: C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively.
STATEMENT 1: You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You can not overload function declarations that differ only by return type.
STATEMENT 2: An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).
Ways to overload a function By changing number of Arguments. By having different types of argument.
Number of Arguments different int sum (int x, int y) { cout << x+y; } int sum(int x, int y, int z) cout << x+y+z; int main() { sum (10,20); // sum() with 2 parameter will be called sum(10,20,30); //sum() with 3 parameter will be called }
Different Datatype of Arguments int sum(int x,int y) { cout<< x+y; } double sum(double x,double y) cout << x+y; int main() { sum (10,20); sum(10.5,20.5); }
EXAMPLE 1:(without class and object) Following is the example where same function calc() is being used
ANS CODE: #include<iostream.h> #include<conio.h> int calc (int); int calc (int,int); int main() { int s,a,b; Cout<<“Enter a number:” Cin>>s; Cout<<“square is:”<<calc(s); Cout<<“Enter two numbers:” cin>>a>>b; Cout<<“addition is:”<<cal(a,b); return 0]; getch(); int calc (int x) { return(x*x); } int calc (int x,int y) return(x+y)
EXAMPLE 2:(using class and object) Following is the example where same function print() is being used to print different data types:
ANS CODE: include <iostream> using namespace std; class printData { public: void print(int i) cout << "Printing int: " << i << endl; } void print(double f) cout << "Printing float: " << f << endl; void print(char* c) { cout << "Printing character: " << c << endl; }; int main(void) { printData pd; // Call print to print integer pd.print(5); // Call print to print float pd.print(500.263); // Call print to print character pd.print("Hello C++"); return 0; }
OUTPUT: When the above code is compiled and executed, it produces the following result: Printing int: 5 Printing float: 500.263 Printing character: Hello C++
END