Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 4

Function Overloading in C++

If multiple functions having same name but parameters of the functions should be different is known
as Function Overloading.
If we have to perform only one operation and having same name of the functions increases the readability
of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the function such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you to understand the behavior of the function because its name differs.
Parameters should be different means
1. Data Type of parameter should be different
Eg:
void add(int, int);
void add(double,double);

void add(int a, int b)


{
cout<<"sum ="<<(a+b);
}

void add(double a, double b)


{
cout<<endl<<"sum ="<<(a+b);
}

main()
{
add(10,2);
add(5.3,6.2);
return 0;
}

1
2. Number of parameter should be different
Eg:
void add(int , int);
void add(int , int, int);

#include<iostream>
using namespace std;

void add(int a, int b)


{
cout<<"sum ="<<(a+b);
}

void add(int a, int b,int c)


{
cout<<endl<<"sum ="<<(a+b+c);
}

main()
{

add(10,2);
add(5,6,4);
return 0;
}

3. Sequence of parameter should be different


Eg:
void add(int , double);
void add(double , int);

2
#include<iostream>
using namespace std;

void add(int a, double b)


{
cout<<"sum ="<<(a+b);
}
void add(double a, int b)
{
cout<<endl<<"sum ="<<(a+b);
}

main()
{
add(10,2.5);
add(5.5,6);
return 0;
}

Eg:
void add(int , int); function overloading does not depend onto the return type
int add(int, int); of the method

Q: Write a class Volume in C++ program to find volume of cube, cylinder and
rectangular box using the concept of function overloading.
Volume of cube=s3; volume of cylinder=pi*r2h; and volume of rectangular box=l*b*h

3
Q: Write a class Draw in C++ program with three draw functions using the concept of
function overloading. The output of that draw method should be as follows:
draw() draw(int) draw(int,char)
*
* *
* * *
* * * *
*

* *

* * *

* * * *

A
A A
A A A
A A A A

You might also like