Operator Overloading in C++

In this C++ tutorial, we are going to discuss the operator overloading and its implementation.

What is Operator Overloading?

The ability of the operator to operate with some special meaning is known as Operator Overloading. This feature of operator overloading is introduced in CPP.

For operator overloading to work at least one of object must be user-defined class object.

Ex:-   ‘+’ operator is used to add two integers . In CPP ‘+’ operator is also overloaded to add two strings also.

int a,b;

a+b;                                  // valid

string s1,s2;

s1+s2;                          // valid

Similarly, ‘+’ operator can be used to add two complex number also in user defined class.

What is the Operator Function?

The name of an operator function is always an operator keyword followed by an operator sign.

Ex:-

 Complex operator + ( Complex const & );

Following operators can not be overloaded in C++

  • Member access or dot operator ( . )
  • Scope resolution operator ( :: )
  • Ternary or Conditional Operator ( ?: )
  • size of 

C++ Code implementation of operator overloading adding two complex numbers

 
#include<bits/stdc++.h>
using namespace std;

   class A
 {
     int real;
     int img;
     
     public:
     
        A(){};
      
         A(int a, int b)
       {
         real=a;
         img=b;
       }
       
         A operator + ( A );
       
         void show()
       {
           cout<<real<<"+"<<img<<"i"<<endl;
       }
 };
 
  A A::operator +(A obj)
 {
     A temp;
     
      temp.real = real + obj.real;
      temp.img  =  img + obj.img;
      
      return temp;
 }
 
   int main()
 {
     
      A c1(1,2);
      A c2(3,4);
  
      A c3=c1+c2;
      c3.show();
 }

OUTPUT

4+6i

Conversion Operator in C++

Conversion operator are use to convert one type to another. It is used for class to basic type conversion.

C++ code implementation of Conversion operator converting class to basic type

#include<bits/stdc++.h>
using namespace std;

   class A
 {
    int a,b;
    
     public :
     
        A(int x, int y)
      {
          a=x;
          b=y;
      }      
      operator float()
      {
          return (float(a)/float(b));
      }
 };
 
  int main()
  {
      A a1(4,3);
      
      float res=a1;
      
      cout<<res;
  }

OUTPUT

1.33333

Also read,

Leave a Reply

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