Operator Overloading in C++

In C++ we can specify more than one definition for a function name or an operator in the same scope. This is called function overloading and operator overloading respectively.

When you call an overloaded function or operator, the compiler determines the most appropriate definition to use. It is also done by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions.

Important points about operator overloading

1) For operator overloading to work, at least one of the operands must be a user defined class object.

2) Assignment Operator: The default assignment operator does assign all members of right side to the left side and works fine in most of the cases (this behavior is same as copy constructor). As a result, the compiler automatically creates a default assignment operator with every class.

3) Conversion Operator: We can also write conversion operators that can be used to convert one type to another type.

4) Any constructor that can be called with a single argument works as a conversion constructor, means it can also be used for implicit conversion to the class being constructed.

EXAMPLE:

For example, we can overload an operator โ€˜+โ€™ in a class like String to concatenate two strings.

#include<iostream>
using namespace std;
  class Complex_no{
private:
    int real, imag;
public:
    Complex_no(int r = 0, int i =0)  {real = r;   imag = i;}

          // This is automatically called when '+' is used between two Complex objects
    Complex_no operator + (Complex_no const &obj) {
         Complex result;
         result.real = real + obj.real;
         result.imag = imag + obj.imag;
         return result;
  }
    void print() { cout << real << " + i" << imag << endl; }
};
  int main()
{
    Complex_no c1(6, 3), c2(7, 5);
    Complex_no c3 = c1 + c2; // An example call to "operator+"
    c3.print();
}

Output:

18 + i8

Overloadable Operators :

We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!๐Ÿ‘‹
Can we help you?