Update appNew update is available. Click here to update.
Last Updated: Jun 30, 2023

Operators Overloading

Author Shivam Verma
3 upvotes

Introduction

Operator overloading provides us a flexible option for the creation of new definitions for most C++ operators. In C++, we can make an operator work for user-defined classes. In simple words, C++ has the ability to provide the operators with special meaning for a data type. This mechanism of giving such special meaning to an operator is known as operator overloading. Operator overloading is a compile-time polymorphism. The main advantage of using operator overloading is to perform different operations on the same operand.

Syntax of operator overloading

return_type class_name operator symbol(arg_list)
{
    function body // body of the function 
}

In the above syntax, 

  • The return_type is the return type of the function.
  • Next, the class_name is the name of the class.
  • The operator is a keyword. 
  • The symbol is preceded by the keyword operator, and the operator symbol is the function name. Operator functions must be either member function or friend function.
  • arg_list is the arguments passed by the function.


Also see, Literals in C.Fibonacci Series in C++

Rules for operator overloading

While operator overloading, we keep in mind the following measures

  1. The only existing operator can be overloaded. New operators can not be overloaded.
  2. Every overloaded operator must contain at least one operand of user-defined datatype.
  3. During operator overloading, we can not change the basic meaning of operators.
  4. If unary operators are overloaded by a member function, then they take no explicit arguments. But if they are overloaded through a friend function, then take one argument.
  5. If binary operators are overloaded by a member function, then they take one explicit argument. But, if they are overloaded through a friend function, then take two arguments.

Operator Overloading in Unary Operators

Unary operators operate on only one operand. The unary operator's examples are increment operator -- and decrement operator ++.

Code

#include<bits/stdc++.h>
using namespace std;
class A
{
    private:
    int x,y;
    public:
    A() {}
    void setdata(int a,int b)
    {
        x=a;
        y=b;
    }
    void operator ++() {
        x=++x;
        y=y+2;
    }
    void operator --()
    {
        x=--x;
        y=y-2;
    }
    void print()
    {
        cout<<x<<" "<<y<<endl;
    }
};
int main()
{
    A op;
    op.setdata(10,15);
    ++op;
    cout << "Incremented numbers are "<<endl;
    op.print();
    --op;
    cout << "Decremented numbers are "<<endl;
    op.print();
    return 0;
}

Output 

Incremented numbers are 
11 17
Decremented numbers are 
10 15

Here, In the above code, when we use ++op, the void operator ++() is called. This increases the 'x' attribute for the object op by one and the 'y' attribute for the object op by 2. when we use --op, the void operator --() is called. This decreases the 'x' attribute for the object op by one and the 'y' attribute for the object op by 2.

Try and compile with online c++ compiler.

Operator Overloading in binary Operators

Binary operators operate on two operands. Let’s understand the operator overloading in the binary operators by the code.

Code

#include <bits/stdc++.h>
using namespace std;
class Complex
{
   private:
    int re;
    int im;
   public:
    Complex(){}
    void setdata(int x,int y)
    {
      re=x;
      im=y;
    }
    // Overload the + operator
    Complex operator+(const Complex& obj){
        Complex temp;
        temp.re=re+obj.re;
        temp.im=im+obj.im;
        return temp;
    }
    void print()
    {
        if (im<0)
            cout<<re<<im<<"i"<<endl;
        else
            cout<<re<<"+"<<im<<"i"<<endl;
    }
};
int main()
{
    Complex comp1,comp2,res;
    cout<<"The first complex number is"<<endl;
    comp1.setdata(10,5);
    comp1.print();
    cout<<"The second complex number is"<<endl;
    comp2.setdata(12,7);
    comp2.print();
   // comp1 calls the operator function
   // comp2 is passed as an argument to the function
    res=comp1+comp2;
    cout<<"The sum of the complex number is"<<endl;
    res.print();
    return 0;
}

Output 

The first complex number is
10+5i
The second complex number is
12+7i
The sum of the complex number is
22+12i

 

Check out this article - Compile Time Polymorphism

Know What is Object in OOPs here in detail.

C++ Operators that can not be Overloaded

Some C++ operators can't be overloaded as follows.

Frequently asked questions

  1. How does the C++ compiler differentiate between overloaded postfix and prefix operators?
    Ans: A postfix operator has a dummy parameter, but a prefix operator has no parameter.
     
  2. What is operator overloading?
    Ans: To assign more than one operation on the same operator is known as operator overloading.
     
  3. How does the operator function differ from the normal function?
    Ans: Operator functions are also the same as the normal functions. The operator function must have an operator keyword followed by the operator 'x, where x is the operator that allows overload.
     
  4. Can I create an operator '**' for "to the power of" operations?
    Ans: No, you can not create an operator '**' for "to the power of" operations because C++ has no operator '**.'

Key Takeaways

We learned about the syntax and the rules of operator overloading in this blog. This blog also discussed the operator overloading in unary and binary operators with the help of the program.

This blog is over, but learning never stops. You can learn more about such programming concepts here. Happy Learning!

Previous article
Function Overloading and Function Overriding
Next article
Introduction to Virtual function