Function and operator overloading

March 22, 2022 · Team EasyExamNotes · 2 min read (est.) · 0 comments

Share on WhatsApp

Function Overloading

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. 

Ways to overload a function:

  1. By changing number of Arguments.
  2. By having different types of argument. 

By Changing Number of Arguments:

int sum(int a,int b)
{      
return a + b;      
}      

int sum(int a, int b, int c)      
{      
return a + b + c;      
}      


By having different types of argument:

int sum(int a,int b)  
{  
    return a+b;
}

float sum(double x, int y)  
{  
    return x+y;  
}  

Operator Overloading

Operator overloading is a compile-time polymorphism. 
As the name indicated the operator is overloaded to provide the special meaning to the user-defined data type. 

For example: Overloading the Unary operator ++

#include <iostream>    
using namespace std;    
class Een 
{    
private:    
int n;    
public:    
Een(): n(4){}    
void operator ++() {
n = n+2;     
}    
void Print() {     
cout<<n;     
}    
};    
int main()    
{    
Een E;    
++E;  // calling of a function “void operator ++()”    
E.Print();    
return 0;    
}    

Discussion

Ask a question, share your thoughts or report an error.

Sign in to participate in the discussion.

Join the discussion