Operator Overloading in C++

In this blog, we will learn about operator overloading in c++. We will have a brief idea about overloading, the need for overloading, types of overloading, and their explanation with examples. Operator overloading is necessary in C++ as we are dealing with classes many times so some normal operators might not work properly for them. Don’t worry we will learn all about them while moving further in the blog.

What is Overloading?

Overloading refers to changing the meaning of an already defined or pre-existing operator or function according to user requirements so that the user can use them accordingly while implementing or performing further operations. They are used in C++ and other programming languages also.

Types of Overloading

There are mainly two types of overloading available in C++ i.e,

  • Function Overloading
  • Operator Overloading

Function Overloading: Function overloading is a term used in the C++ programming language to describe when two functions with the same name exist in the same piece of code but each with a distinct set of arguments.

Operator Overloading: Operator overloading is a sort of compile-time polymorphism where the operator is overloaded to provide the user-defined data type with a specific meaning. The operation on the user-defined data type is carried out using it. Most of the C++ operators are overloaded or redefined via operator overloading.

What are Operators in C++?

You must have encountered a lot of operators while working in any programming language but you might know yet that these are operators. In simple words, the operators are the symbols that perform logical or mathematical operations or computations on variables or values. There are many types of operators some of them are

  • Airthemetic Operators: +, -, *, /, %.
  • Relational Operators: ==, !=, <=, >=.
  • Bitwise Operators: |,&, <<, >>.
  • Assignmnet Operators: +=, -=, *=, /=.
  • Logical Operators: ||, &&, !.
  • Other Operators: sizeof, typeid.

Operator Overloading in C++

By now you might have a brief idea about what operator overloading is but here we will learn about the need for operator overloading in C++.
The need for operator overloading in C++
Here let’s see the example of operator overloading. Since we know the use of the ‘+’ operator is addition. For Example:

 float a;
 int b, sum;
 sum = a+b;

In the above example we can see that a is a float type variable whereas b and sum are integer type variables so the line sum = a+b will not create any problem as both the data types i.e, float and sum are predefined so there will be no objection as the + operator knows what to do with the pre-defined data types.
But, Look in the example below:

class E
{
};
int main()
{
      E   e1,e2,e3;
      e3= e1 + e2;
      return 0;
}

Now look at the above example we have created a class with the name E and in the main function we are creating an object with the name e1, e2, e3 and performing the + operator on them. But now the line will give an error as we do not know what to do with objects of a user-defined class we are not performing operations on predefined data types we are performing operations on user-defined classes and objects. In these types of scenarios operator overloading in C++ comes into play as we can define the use case and function of operators in the class itself.

Operators that cannot be Overloaded in C++

Most of the operators can be overloaded in c++ and can be used in operator overloading in c++. But some of them cannot be used in operator overloading in c++.

Some of the examples are

  • sizeof
  • typeid
  • dot operators
  • Scope resolution

Now we will look at the reasons why they can’t be used in operator overloading in c++.

  1. sizeof: The size of the object or datatype used as the operand is returned by this. The compiler evaluates this; real-time evaluation is not possible. The sizeof operator is implicitly required for the correct incrementing of a pointer in an array of objects. A basic aspect of the language would disintegrate if its meaning were changed by overloading.
  2. Scope Resolution(::) : By mentioning a namespace, this aids in identifying and defining the context to which an identifier relates. It uses names rather than values and is entirely evaluated at runtime. The operands of scope resolution are note expressions with data types, and if CPP were overloaded, it lacks the syntax to capture them. So it is not feasible to overload this operation syntactically.
  3. typeid: A CPP application may now retrieve the true derived type of an object that is being pointed to via a pointer or reference. The purpose of this operator is to specifically specify a type. Polymorphism can be used to make a user-defined type "appear" like another type, but the typeid operator’s meaning must not change to avoid serious problems.
  4. Class member access operator: We can use them in dealing with complex numbers or assigning values through constructors.
  5. Ternary Operators: These are the short form of “if-else” conditions and if we overload the operator that will not guarantee that now we are dealing with the right expression. Hence the ternary operator can not be used in operator overloading in C++.

Syntax for Operator Overloading

class nameofclass{
    public
       returnType operator symbol (arguments) {
       } 
};
  • The nameofclass is the name of the user-defined class.
  • returntype is the return type of the function.
  • operator is a keyword, you have to write it as it is.
  • symbol here you have to insert the symbol that you want to use in operator overloading in c++.
  • arguments these are the arguments passed to the function.

Operators that can be Overloaded in C++

Most of the operators can be overloaded in C++ some of them are shown below:

Examples of Unary Operator Overloading in C++

Unary operators are those operators that need only one operand to work like ++,–.
In the example below we will look at how to use it as a unary operator in operator overloading

Code implementation in C++

// Overload ++ when used as prefix

#include <iostream>
using namespace std;

class Count {
   private:
    int value;

   public:

    Count() : value(51) {}

    void operator ++ () {
        ++value;
    }

    void display() {
        cout << "Count: " << value << endl;
    }
};

int main() {
    Count count1;

    ++count1;

    count1.display();
    return 0;
}

Output

The output of the above-given code will be

Explanation of the Example of an operator overloading in C++
In the above example we are using operator overloading in C++ of “++” operator. The ++ operator is used to increase the value by 1. Here we are using the ++ operator as a prefix hence first the value will be increased then it will be passed to other instructions.
We need operator overloading as here we are using the ++ operator in class hence we are defining or overloading the ++ operator in class. By following the above-mentioned syntax. The initial value was 51 and after the operation, it will be 52 hence shown in the output.

Examples of Binary Operator Overloading in C++

Binary Operators are those operators which need two operands to work and perform further operations like +. In the example below we will see the addition of complex numbers that are not predefined in the library we have to create a new class and overload the + operator, which is known as operator overloading in C++.

Code implementation in C++

#include <iostream>
using namespace std;
 
class ComplexNumber{
  private:
  int real;
  int imaginary;
  public:
  ComplexNumber(int real, int imaginary){
    this->real = real;
    this->imaginary = imaginary;
  }
  void print(){
    cout<<real<<" + i"<<imaginary;
  }
  ComplexNumber operator+ (ComplexNumber c2){
    ComplexNumber c3(0,0);
    c3.real = this->real+c2.real;
    c3.imaginary = this->imaginary + c2.imaginary;
    return c3;
  }
};
int main() {
    ComplexNumber c1(4,3);
    ComplexNumber c2(5,7);
    ComplexNumber c3 = c1 + c2;
    c3.print();
    return 0;
}

Output

The output of the given code will be as shown below:

Explanation of the above Example
In the above example we are using operator overloading in c++ of the binary operator.
So in the above examples, we are dealing with complex numbers we have created a class with the name ComplexNumbers and are performing operations in it. We are not used to writing the + operator for complex numbers in programming languages so we are operator overloading in it.
We have followed the syntax and overloaded the + operator and with the given input of complex numbers we are getting the required output which is adding the imaginary part to the imaginary part and the real part to the real part as you can see in the output and representing the result in another complex number.

Canonical Implementation

The question might arise in your mind that in operator overloading in C++ can we overload the operator to any function? The answer is yes but you are advised to overload the operator as close as to the original meaning or function of the operator.

Advantages of Operator Overloading in C++

  • We can provide similar syntax data types to the user.
  • Operator overloading in c++ allows the user to use the operator or notation closer to its actual meaning.
  • It will increase the understanding of users and is very beneficial for large codes.

Disadvantages of Operator Overloading in C++

  • The order of precedence of the operators cannot be changed.
  • We can only overload the pre-existing operator and cannot overload the new operator.
  • We cannot change the arity of operators.

Conclusion
In the above article, we have studied operator overloading in c++, the operators which cannot be overloaded, and the operators which can be overloaded. We have also looked at the examples of unary and binary operators and see how to use them in operator overloading in c++ with proper code and explanation followed by the advantages and disadvantages of operator overloading in c++.

Leave a Reply

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