FUNCTION
OVERLOADING
A PART OF POLYMORPHISM
CONTEXT
What is function overloading.
Why we use function overloading.
Way of implementation
Merit & demerits..
FUNCTION OVERLOADING
Define multiple functions with the
same name differing in the number
of arguments passed.
If any class have multiple functions
with same names but different
parameters then they are said to be
overloaded. Function overloading
allows you to use the same name for
different functions, to perform,
either same or different functions in
the same class.
WHY WE USE FUNCTION
OVERLOADING
We use function overloading/method overloading for
the purpose of:
1. Compile time binding
2. Better Consistency
3. Better Readability
WAY OF IMPLEMENTATION
The implementation of method overloading can be
explained as follows:
Area of geometrical shape
Area(breadth ,
Area(radius) Area(side)
width)
Breadth * width
(side)^2
2* radius
MERITS & DEMERITS
Merits:
Consistency
Readability
Better performance
Demerits
Sometime ambiguous
Ways to overload a function
By changing number of Arguments.
By having different types of argument.
Rules for using Default Arguments
Only the last argument must be given default value. You
cannot have a default argument followed by non-default
argument.sum (int x,int y); sum (int x,int y=0); sum (int
x=0,int y); // This is Incorrect
If you default an argument, then you will have to default
all the subsequent arguments after that.sum (int x,int
y=0); sum (int x,int y=0,int z); // This is incorrect sum
(int x,int y=10,int z=10); // Correct
You can give any value a default value to argument,
compatible with its datatype.
Placeholder Arguments
When arguments in a function are declared without any
identifier they are called placeholder arguments.
void sum (int,int); Such arguments can also be used with
default arguments.
void sum (int, int=0);
Following is the example where same function print() is
being used to print different data types:
#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 pd.print(‘a’);
}
character pd.print("Hello C++"); return 0; }When the
above code is compiled and executed, it produces the
following result:
Printing int: 5 Printing float: 500.263 Printing character:
Hello C++.