0% found this document useful (0 votes)
17 views

3.5 Function Overloading

Uploaded by

hetavimodi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

3.5 Function Overloading

Uploaded by

hetavimodi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Function Overloading

--Prof. S.N.Shelke
C++ Overloading

 If we create two or more members having the same name but different

in number or type of parameter, it is known as C++ overloading. In C++,


we can overload:

1. methods,

2. constructors, and

 It is because these members have parameters only.


Function Overloading

 Function Overloading is defined as the process of having two or more

function with the same name, but different in parameters is known as


function overloading in C++.

 In function overloading, the function is redefined by using either different

types of arguments or a different number of arguments. It is only


through these differences compiler can differentiate between the
functions.
#include <iostream>
using namespace std;
class Cal {
public:
int add(int a,int b){
return a + b;
Output:
}
int add(int a, int b, int c) 30
{ 55

return a + b + c;
}
};
int main() {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Function Overloading and Ambiguity

 When the compiler is unable to decide which function is to be invoked

among the overloaded function, this situation is known as function


overloading.

 When the compiler shows the ambiguity error, the compiler does not run

the program.
#include <iostream>
using namespace std;
class Cal
{
public:
void add(int a,int b)
{
int ans=a+b+100;
cout<<a+b<<endl;
}
void add(float x, float y)
{
float ans=x+y+200;
cout<<ans<<endl;
}
};
int main()
{
Cal C; Output:
int y=10;
C.add(10,20); 130
return 0;
}
#include <iostream>
using namespace std;
class Cal
{
public:
void add(int a,int b)
{
int ans=a+b;
cout<<a+b<<endl;
}
void add(int x, int y, int z=5)
{
float ans=x+y+z;
cout<<ans<<endl;
}
};
int main()
{
Cal C;
int y=10;
C.add(10,20,30);
C.add(10,20);
return 0;
}
#include <iostream>
using namespace std;
class Cal
{
public:
void add(int x)
{
x=x+100;
cout<<x<<endl;
}
void add(int &p)
{
p=p+200
cout<<p<<endl;
}
};
int main()
{
Cal C;
int y=10;
C.add(y);
return 0;
}
Prof. S. N. Shelke
(Assistant Professor)
Department of Computer
Engineering
Sinhgad Academy of Engineering,
Kondhwa, Pune

You might also like