Operators Overloading in C++

Operators Overloading in C++

Operators overloading in C++ is a type of polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform operations on the user-defined data types. 

However, there are a few operators which cannot be overloaded they are follows

    • Scope operator – ::
    • Sizeof
    • Member selector – .
    • Member pointer selector – *
    • Ternary operator – ?:

Syntax of Operator overloading in C++

return_type class_name  : : operator op(argument_list)  
{  
     // body of the function.  
}

 

There are two types of Operator Overloading

    1. Unary Operator Overloading
    2. Binary Operator Overloading

 

1. Unary Operator Overloading

Unary operator overloading operates a single operand for example The increment (++) and decrement (–)

 Program to overload the unary operator

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

Output

The Count is: 7

2. Binary Operator Overloading

The binary operator overloading takes two arguments.The binary operators are addition (+), subtraction (-), division (/) operator etc.

 

Program to overload the binary operators.

#include <iostream>  
using namespace std;  
class A  
{  
    
    int x;  
      public:  
      A(){}  
    A(int i)  
    {  
       x=i;  
    }  
    void operator+(A);  
    void display();  
};  
  
void A :: operator+(A a)  
{  
     
    int m = x+a.x;  
    cout<<"Addition of two objects is : "<<m;  
  
}  
int main()  
{  
    A a1(5);  
    A a2(4);  
    a1+a2;  
    return 0;  
}  

Output

Addition of two objects is : 9 

 

Read more, Object and Function in C++

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *