CPP Programming

All Languages C CPP JAVA HTML CSS JAVASCRIPT PYTHON

Oerloading(Function and Operator) In Cpp

If we create two or more members having same name but different in number or type of parameter, it is known as C++ overloading. In C++, we can overload: methods, constructors, and indexed properties It is because these members have parameters only.

Types of overloading in C++ are:

C++ Function Overloading

Having two or more function with same name but different in parameters, is known as function overloading in C++.
The advantage of Function overloading is that it increases the readability of the program because you don't need to use different names for same action.

C++ Function Overloading Example:

Let's see the simple example of function overloading where we are changing number of arguments of add() method.

#include <iostream>  
using namespace std;  
class Cal {  
    public:  
static int add(int a,int b){    
        return a + b;    
    }    
static int add(int a, int b, int c)    
    {    
        return a + b + c;    
    }    
};   
int main(void) {  
    Cal C;  
    cout<<C.add(10, 20)<<endl;    
    cout<<C.add(12, 20, 23);   
   return 0;  
}  

Output:
30
55

C++ Operators Overloading

Operator overloading is used to overload or redefine most of the operators available in C++. It is used to perform operation on user define data type.
The advantage of Operators overloading is to perform different operations on the same operand.

C++ Operators Overloading Example

Let's see the simple example of operator overloading in C++. In this example, void operator ++ () operator function is defined (inside Test class).

#include <iostream>  
using namespace std;  
class Test  
{  
   private:  
      int num;  
   public:  
       Test(): num(8){}  
       void operator ++()   
       {   
          num = num+2;   
       }  
       void Print() {   
           cout<<"The Count is: "<<num;   
       }  
};  
int main()  
{  
    Test tt;  
    ++tt;  // calling of a function "void operator ++()"  
    tt.Print();  
    return 0;  
}  

Output:
The Count is: 10