CPP Overloading

CPP overloading can be defined as the process of creating two or more members (methods, constructors and indexed properties) with same name and having parameters only but are different in number or type of parameter.

 

Types of CPP overloading:

 Function overloading:

In order to increase the readability of a program, function overloading is used. In function overloading, it is not necessary to use different names for same action. In CPP, Function overloading is achieved by using two or more functions in a program with same name but different in parameters

Operators overloading:

In order to perform different operations on the same operand, operator overloading is used. In operator overloading, operations are performed on user defined data type to overload or redefine most of the CPP operators.

 

Example 1: Example of Function Overloading

#include <iostream.h>  
using namespace std;  
class multiply
{  
public:  
static int mul(int a,int b)
{    
return a * b;    
}    
static int mul(int a, int b, int c, int d)    
{    
return a * b * c * d;    
}    
};   
int main(void) {  
multiply C;  
cout<<C.mul(50, 60)<<endl;    
cout<<C.mul(10, 20, 30, 40);   
return 0;  
}

Output

3000        
240000

Example 2: Example of Operators Overloading

#include <iostream.h>  
using namespace std;  
class cal
{  
private:  
int n;  
public:  
cal(): n(10){}  
void operator --()   
{   
n = n-5;   
}  
void Display() {   
cout<<n;   
}  
};  
int main()  
{  
cal c;  
--c;  
c.Display();  
return 0;  
}

Output

5
Please follow and like us:
Content Protection by DMCA.com