C++ Laguage



Admission Enquiry Form

  

Function Overloading/Polymorphism in C++:




What is Function Overloading?

First we need to understand the concept of overloading in real world.

Overloading in real world is more than capability or capacity. for example if two persons are sitting on bike then it is not overloaded but if three are sitting then we can say the bike is overloaded. in other example if a person is capable to do one job but he is doing more than one jobs then we can say the person is overloaded by work.

Now we have to think about overloading in C++.Just try to think who does job or work or task or function in C++ Program or class. Ofcourse you can say function of member function in C++ class.

So overloading means when a function or member function is performing more than one task in C++ class.

How that is possible ?

That is possible if we are allowed to create more than one functions of same name

Example : sum(); and sum(10,20);sum('s','g');sum(10,20,30);

Here you may have noticed that function name is same but the arguments of the function are different so please notice this you can use same name for more than one functions but arguments must be different so that compiler can differentiate the functions when binds the functions call to the definition of the function or body of the function.

 



Code for Function Overloading in C++.

#include<iostream>
using namespace std;
class Maths
{
int num1,num2,res;
public:
void sum()
{
cout<<"Enter first number ";
cin>>num1;
cout<<"Enter second number ";
cin>>num2;
res=num1+num2;
cout<<"\nsum()= "<<res;
}
void sum(int n1,int n2)
{
res=n1+n2;
cout<<"\nsum(n1,n2)= "<<res;
}
void sum(float x,float y)
{
float ans;
ans=x+y;
cout<<"\nsum(x,y)= "<<ans;
}
};
int main()
{
Maths mt;
mt.sum();
mt.sum(10,20);
mt.sum(10.3,20.5);
}

Output:

The above code will generate an error i.e. error: call of overloaded 'sum(double, double)' is ambiguous due to 'void Maths::sum(int, int)' and 'void Maths::sum(float,float)' because float can store integer value but integer can-not store float.So we will write only one function with two float arguments.



Code for Function Overloading with the Function sum(float,float) arguments in C++.

#include<iostream>
using namespace std;
class Maths
{
int num1,num2,res;
public:
void sum()
{
cout<<"Enter first number ";
cin>>num1;
cout<<"Enter second number ";
cin>>num2;
res=num1+num2;
cout<<"\nsum()= "<<res;
}
void sum(float x,float y)
{
float ans;
ans=x+y;
cout<<"\nsum(x,y)= "<<ans;
}
};
int main()
{
Maths mt;
mt.sum();
mt.sum(10,20);
mt.sum(10.3,20.5);
}

Output:

Enter first number 100
Enter second number 200

sum()= 300
sum(x,y)= 30
sum(x,y)= 30.8