Unlock the complete
Logicmojo experience for FREE

1 Million +

Strong Tech Community

500 +

Questions to Practice

50 +

Jobs Referrals

Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Top tech companies experts provide live online training

Learn Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Logicmojo - Updated Jan 11, 2024



In C++, operator overloading is a crucial idea. An operator is overloaded to give it a user-defined meaning in this sort of polymorphism. The user-defined data type is operated on using the overloaded operator. The "+" operator, for instance, can be overloaded to perform addition on a variety of data types, such as String(concatenation), Integer, etc.

Operator overloading, to put it simply, is a compile-time polymorphism in which the operator is overloaded to give the user-defined data type a special meaning. Most of the C++ operators are overloaded or redefined via operator overloading. The operation on the user-defined data type is carried out using it. For instance, C++ has the capability of adding user-defined data type variables to the built-in data types.
In other words, overloaded operators are functions with unique names that start with the keyword operator and end with the symbol for the declared operator. An overloaded operator has a return type and an argument list just like any other function.

What do C++ operators do?

The operator symbol is used in all programming languages, including C++, to execute mathematical and logical computations on a value or/and a variable. Or, to put it another way, "Operator operates operands."

      ⮞ Arithmetic Operators: +,+, -,−, /,/, *,∗, \%%

      ⮞ Assignment Operators: +=,+=, -=,−=, /=,/=, *=,∗=, \%=%=

      ⮞ Relational Operators: ==,==, !=,!=, >=,>=, <=, etc.<=,

      ⮞ Logical Operators: \&\&,&&, ||,∣∣, !!

      ⮞ Bitwise Operators: \&,&, |,∣, >>>>, <<, etc.

      ⮞ Other Operators:sizeof, ?: etc

What does C++'s operator overloading mean?

The term "Operator Overloading" refers to the ability provided by C++ to define multiple definitions for an operator inside the same scope. In essence, it is the process of adding new features and behaviours to already-existing C++ operators. These operators only operate by default on common data types like int, float, char, void, etc.
Since overloading happens at compile time in C++, it is equivalent to static binding or compile-time polymorphism.
Implementing operator overloading in C++ syntax:

class className { 
    ... .. ... 
    public 
       returnType operator symbol(parameters) { 
           ... .. ... 
       }  
    ... .. ... 
}; 

Operator overloading in C++ is necessary

It enables templates to function equally well with classes and built-in types and enables us to give our class users with an intuitive interface. C++ operators can have user-defined meanings on user-defined types or classes thanks to operator overloading.

Types Overloading in C++

What is overloading a function?

Function overloading is the practise of having two or more functions with the same name but differing parameters (arguments). Either a different number of arguments or a new type of parameter is used to redefine the function. A compiler can only distinguish between functions through these variations.

How does operator overloading work?

The functionality and behaviour of already-existing operators, such as mathematical and other operations, can be enhanced in C++ by the addition of special features. Operator overloading is the process of giving an operator a special meaning. For instance, we can concatenate two strings by simply using + to overload the operator "+" in a class-like string.

Implementation of Operator Overloading in C++

An operator function is a term for an overloaded operator. Although it is identical to regular functions, an operator function's name always consists of the operator keyword and the operator symbol (such as +,-,*, etc.). The types and number of operands used with the operator allow us to distinguish between many overloaded functions of the operator.
Operators may be globally overloaded (by using the non-member function) or individually for each class (using the member or friend function). Operator overloading can be implemented in three different ways:

      ⮞ The left operand must be an object of the class in order for the operator overloading function to qualify as a member function. Unary operators in this type have an empty parameter list, whereas binary operators only have one argument.

      ⮞ If the operator overloading function needs access to a class's private and protected members, it can be made a friend function. In this type, binary operators have two arguments, whereas unary operators only have one.

      ⮞ Non-member function: The operator overloading function must be a non-member function if the left operand differs.

Unary operators' overloading

Let's first define what unary operators are. Unary operators, as their name suggests, operate on a single operand. Examples are logical not (! ), Decrement (--), and Increment (++).
Here is an illustration of how unary operators can be overloaded.

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



Learn More

Examples of C++ Operator Overloading: Arithmetic Operator +
Example #3:
In C++, arithmetic operators are most frequently employed. To perform arithmetic operations on user-defined data types, almost all arithmetic operators can be overloaded.
To add to Time(hh:mm:ss) objects, the + operator has been overridden in the example below.

# include<iostream>
using namespace std;    
class Time
{      int h,m,s;
       public:
       Time()
       {
        h=0, m=0; s=0;
       }
       void setTime();
       void show()
       {
         cout<< h << ":"<< m<< ":"<< s;
       }
       //overloading '+' operator
       Time operator+(time);   
};
Time Time::operator+(Time t1)	//operator function
{
       Time t;
       int a,b;
       a = s+t1.s;
       t.s = a%60;
       b = (a/60)+m+t1.m;
       t.m = b%60;
       t.h = (b/60)+h+t1.h;
       t.h = t.h%12;
       return t;
}
void time::setTime()
{
       cout << "\n Enter the hour(0-11) ";
       cin >> h;
       cout << "\n Enter the minute(0-59) ";
       cin >> m;
       cout << "\n Enter the second(0-59) ";
       cin >> s;
}
void main()
{
       Time t1,t2,t3;
       cout << "\n Enter the first time ";
       t1.setTime();
       cout << "\n Enter the second time ";
       t2.setTime();
       t3 = t1 + t2;	//adding of two time object using '+' operator
       cout << "\n First time ";
       t1.show();
       cout << "\n Second time ";
       t2.show();
       cout << "\n Sum of times ";
       t3.show();
       getch();
 }

Operator functions differ from normal functions

Normal functions and operator functions are quite similar in many ways. The function name in conventional functions is replaced by the operator symbol in operator functions, which is the only difference between the two.

Can All Operators Be Overloaded?

Except for a few, almost all operators are susceptible to overload. The following operators cannot be overloaded in C++.
. (dot operator)
:::: (Scope resolution operator)
?:?: (Ternary operator)
sizeof
No fundamental reason exists to forbid overloading of Simply said, C++'s creator Bjarne Stroustrup didn't think it was necessary to provide the unique situation of overloading a ternary operator.

Benefits and Drawbacks of Operator Overloading Benefits

      ⮞ Users can utilise notation that is more closely related to the target domain thanks to operator overloading in C++. For instance, we can write CN1 + CN2 instead of CN1 to add two complex integers. add(CN2) is possible if the class's add function is defined.

      ⮞ User-defined data types may also be provided with syntax that is similar to that of built-in data types.

      ⮞ It makes the programme simpler for others to understand, especially when there is a larger code base.

Dis-advantages

      ⮞ There is no overloading of new operators. Operators that already exist cannot be overloaded.

      ⮞ The operators' sequence of precedence cannot be altered

      ⮞ The operators' arity cannot be altered. For any certain data type, for instance, we cannot perform a+b+ca+b+c.

Rules for Overloading

The following guidelines must be taken into account when overloading operators in C++:

      ⮞ There must be at least one user-defined datatype among the operands.

      ⮞ Only operators that are built-in can be overloaded. In other words, only the existing operators can be overloaded; new operators cannot be formed.

      ⮞ Except for the empty parameter list "()," overloaded operators cannot have default parameters.

      ⮞ Operator precedence and associativity are unaffected by operator overloading.

      ⮞ The quantity of operands cannot be altered. Binary operator stays binary, unary operator stays unary, etc.

      ⮞ Operators can be used in any way when they are overloaded. To make our code easy to comprehend, however, operator overloading must be used appropriately and consistently.

      ⮞ We do not need to write an operator function for the assignment operator =. In C++, it is already overloaded by design. In other words, the = operator can be used directly to clone objects of the same class (a concept similar to the copy constructor. The compiler automatically produces a default assignment operator with every class.

      ⮞ Some operators cannot be overloaded using the friend function. The member function, however, allows for the overloading of such operators.

Special Operators Overloading

The following operators are known as special operators -
new - Used to allocate the memory dynamically.
delete is a tool for dynamic memory release.
[] and () - Subscript operators
-> - Member access operators.

The following operators are referred regarded as "special operators":

Other from the ones already mentioned, operators might be overburdened both as members and as non-members. However, non-member overloading is advised generally. Because:
Symmetry: Objects must serve as the operands of a binary operator when it is specified as a class method. Because the expression 5*complex is illogical, we should write complex*5, not 5*complex. To put it another way, a*b should be equivalent to b*a. If not, it violates the user's expectation that the *operator will be cumulative. Therefore, in this situation, we should overload no-member operators.
Because a non-member method cannot access a private member, there is a tendency for the class to have weak coupling.

Binary Operator Overloading

For user-defined objects, we can change the way the binary operators behave. The two-operand binary operators include addition (+), multiplication (*), and other operations. In this polymorphic compile technique, a single operator can perform a wide range of operations utilising two operands supplied by the programmer or user.
Let's look at the C++ code below as an illustration of how the addition operator can be overloaded.

#include <iostream>
using namespace std;

class Time {
   private:
    int hour;
    int minute;

   public:
    Time() : hour(0), minute(0) {}

    void in() {
        cout << "Enter the time: ";
        cin >> hour;
        cin >> minute;
    }

    // Overload the + operator
    Time operator + (const Time & obj) {
        Time temp;
        temp.hour = hour + obj.hour;
        temp.minute = minute + obj.minute;
        if (temp.minute>=60)
        {
            temp.hour+=1;
            temp.minute-=60;
        }
        if (temp.hour>24)
        temp.hour=1;
        return temp;
    }

    void out() {
      cout<<"Time is "<< hour<<"hrs "<<minute<<"min";
    }
};

int main() {
    Time T1, T2, result;

    cout << "Enter first time in hours and minutes one by one :\n";
    T1.in();

    cout << "Enter second time in hours and minutes one by one :\n";
    T2.in();

   // T1 calls the operator function
   // T2 is passed as an argument to the function
    result = T1 + T2;
    result.out();

    return 0;
}

Important information on operator overload

      ⮞ At least one of the operands must be a user-defined class object for operator overloading to function.

      ⮞ Assignment Operator: Every class has a default assignment operator that is automatically created by the compiler. Most of the time, the default assignment operator works well since it assigns all right side members to the left side (this behaviour is same as copy constructor). For more information, see this.

      ⮞ Conversion Operator: In order to convert one type to another, conversion operators can also be created.

      ⮞ Conversion operators that are overloaded must be a member method. Members of other operators or global methods are both possible.

      ⮞ The quantity of operands cannot be altered. Binary operator stays binary, unary operator stays unary, etc.

      ⮞ Operators can be used in any way when they are overloaded. To make our code easy to comprehend, however, operator overloading must be used appropriately and consistently.

      ⮞ We do not need to write an operator function for the assignment operator =. In C++, it is already overloaded by design. In other words, the = operator can be used directly to clone objects of the same class (a concept similar to the copy constructor. The compiler automatically produces a default assignment operator with every class.

      ⮞ Some operators cannot be overloaded using the friend function. The member function, however, allows for the overloading of such operators.

      ⮞ Any fconstructorthat accepts a single argument and functions as a conversion fconstructorcan be used to perform implicit conversion to the class being created.

FAQs

What does C++'s operator overloading mean?

In this kind of polymorphism, an operator is overloaded to give it the user-defined semantics. In C++, the ability to define numerous definitions for a function name or an operator in the same scope is referred to as function overloading and operator overloading, respectively.

In CPP, is operator overload possible?

The built-in operators in C++ can typically have their functions redefined or overloaded. These operators may be overloaded on the whole as well as by class. Overloaded operators may be global or member functions that are embedded as functions.

What does operator overloading mean?

Object-oriented systems allow the use of the same operator name or symbol for a variety of distinct operations, which is a type of polymorphism known as operator overloading. In other words, it makes it possible for the operator name or symbol to be associated with numerous operator implementations.

What are the different types of operator overloading?

Operator overloading is the process of modifying the functionality of a few particular operators to perform a new task. Operator overloading can have the following forms or approaches:
Overloading of unary operators
Overloading of binary operators
Binary operator overload using the friend function (friend keyword is used to declare the class scope within a function)

Why does OOP employ operator overloading?

Operator overloading makes it simpler to declare a user-defined implementation for such operations when either one or both operands belong to a user-defined class or structure type. As a result, user-defined types behave more like the fundamental raw data types.

What does oops' polymorphism mean?

Polymorphism, one of the core concepts of object-oriented programming (OOP), deals with situations where something might happen in various ways. It alludes to the notion in computer science that multiple types of things can be accessed using a single interface.

What benefits might operator overloading provide?

It enables you to give users of your class with an intuitive user interface and makes it possible for templates to work equally well with classes and built-in/intrinsic types. Thanks to operator overloading like classes, C/C++ operators can have user-defined meanings on user-defined types.

What distinguishes operator overloading from function overloading?

An operator's basic operational meaning could be built upon when it gets overloaded. On the other hand, by using function overloading, we can design a method so that it can be invoked in a variety of ways (also known as method overloading).

Conclusions

This concludes our discussion of "Operator Overloading in C++" I sincerely hope that you learned something from it and that it improved your knowledge. You can consult the C++ Tutorial if you want to learn more about C++.

Good luck and happy learning!