Operator overloading in C++ programming

In C++, operators like '+', '-' have specified functions for native data-types. For example, division operator "/" divides two integers when used as a / b. But, the functions of these operators can also be extended for user-defined data-types as well, this is known as Operator Overloading.

For example:

Suppose we have two objects B and C of class Point containing integer properties x and y. The two properties represent x and y co-ordinates of a point respectively. The addition operator "+" can be overloaded to add the x co-ordinate of B with x co-ordinate of C and add corresponding y co-ordinates.

Overloading an operator can extend the semantics of an operator but we can't change its syntax i.e. the grammatical rule that controls its use such as number of operands, precedence and associativity remains same. For example, addition operation takes 2 operand, precedence of division is greater than addition and so on. Operator overloading is achieved with the help of operator function.

Syntax of Operator Overloading

returntype classname :: operator operator_to_overload ([parameter])
{
    statement(s);
    ... ... ...
}

Operator function must be either friend function or non static member function. If the operator function is a friend function then it will have one argument for unary operator and two argument for binary operator. If the operator function is a non static member function then it will have no arguments for unary operators and one argument for binary operators.

Where Operating Overloading is used?

In C++, whatever we can do by overloading an operator can be done without operator overloading. But operator overloading is used because it makes program more readable as the operator which are used for basic data types can also be used for user-defined data types. For example, consider a program that adds two complex number. To achieve this, we can create a friend function named add() that adds two complex number and return the result. We can call this function as,

c = add(c1,c2);

Here, c1 and c2 are two complex number to be added and c holds the result returned by the function. c, c1 and c2 are objects of a class complex. Using operator overloading, we can replace the calling statement as,

c = c1+c2;

This statement gives more sense and user can clearly understand that two complex numbers are being added. Further statements like

z = add(mult(a,b),sub(x,y));


can be replaced by

z = (a*b)+(x-y);

Rules for operator overloading

  1. Only existing member can be overloaded. We can't create our own operator to overload.
  2. The overloaded operator must have at least one operand of user-defined type.
  3. Overloaded operators follow the syntax rules of original operators. This means we can't change the basic meaning of an operator.
  4. Some operators can't be overloaded. They are: member access operator (.), pointer to member access operator (.*),  scope resolution operator (::), size operator (sizeof), ternary operator (? :).
  5. We can't use friend function to overload some operators. They are: assignment operator (=), function call operator (()), subscripting operator ([]), class member access operator (->).
  6. If the operator function is a friend function then it will have one argument for unary operator and two argument for binary operator. If the operator function is a non static member function then it will have no arguments for unary operators and one argument for binary operators.
  7. When binary operators are overloaded through member function, the left hand operand must be an object of the relevant class.
  8. Binary arithmetic operators such as +, -, *, / must explicitly return a value.

Examples of Operator Overloading

1. C++ program to overload unary minus (-) operator.

#include <iostream>
#include <conio.h>
using namespace std;

class example
{
    int a,b;
    public:
        void input()
        {
            cout<<"Enter a and b: ";
            cin>>a>>b;
        }
        void operator -()   //operator function as a member function
        {
            a=-a;
            b=-b;
        }
        void display()
        {
            cout<<"a="<<a<<endl<<"b="<<b<<endl;
        }
};

int main()
{
    example e;
    e.input();
    cout<<"Before overloading unary minus operator"<<endl;
    e.display();
    -e;
    cout<<"After overloading unary minus operator"<<endl;
    e.display();
    getch();
    return 0;
}

Friend function can also be used as operator function as:

friend void operator -(example s)
{
    s.a=-s.a;
    s.b=-s.b;
}

This program shows how to overload unary minus operator. As per the rule, if non static member function is used, it will take no argument and if a friend function is used as operator function, one argument is required. The statement ' -e; ' calls the operator function. If the operator function is friend function then the object e is the argument itself. Inside the operator function, the sign of data is changed. Hence, unary minus operator is overloaded.

Output

Enter a and b: 13 -9
Before overloading unary minus operator
a=13
b=-9
After overloading unary minus operator
a=-13
b=9

2. C++ program to overload subscript operator [ ] operator

#include <iostream>
#include <conio.h>
using namespace std;

class example
{
    int data[5];
    public:
        void input()
        {
            int i;
            cout<<"Enter 5 integers:"<<endl;
            for(i=0;i<5;i++)
                cin>>data[i];
        }
        int &operator[](int i) // operator function
        {
            return data[i];
        }
};

int main()
{
    int i,sum=0;
    example a;
    a.input();
    cout<<"Calculate sum by overloading [] operator"<<endl;
    for(i=0;i<5;i++)
    {
        sum=sum+a[i]; // calling operator function
    }
    cout<<"Sum = "<<sum;
    getch();
    return 0;
}

Subscript operator [ ] operator is used to access the elements of array. Here, subscript operator is overloaded to access the array of data of class example. Friend function can't be used to overload this operator. 

Output

Enter 5 integers:
15
-8
4
31
9
Calculate sum by overloading [] operator
Sum = 51

Things to know

We can overload all C++ operators except the following:

  • Member access operator (.)
  • Pointer to member access operator (.*)
  • Scope resolution operator (::)
  • Size operator (sizeof)
  • Ternary operator (? :)

These operators can't be overloaded because these operators take names (e.g. int, class name) as their operand instead of values.