Download presentation
Presentation is loading. Please wait.
1
TOPIC: FUNCTION OVERLOADING
2
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.
3
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.
4
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).
5
Ways to overload a function
By changing number of Arguments. By having different types of argument.
6
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 }
7
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); }
8
EXAMPLE 1:(without class and object) Following is the example where same function calc() is being used
9
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)
10
EXAMPLE 2:(using class and object) Following is the example where same function print() is being used to print different data types:
11
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( ); // Call print to print character pd.print("Hello C++"); return 0; }
12
OUTPUT: When the above code is compiled and executed, it produces the following result: Printing int: 5 Printing float: Printing character: Hello C++
13
END
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.