Monday, October 20, 2014

C++ Operator Overloading

C++ Operator Overloading

The meaning of operators are already defined and fixed for basic types like: int, float, double etc in C++ language. For example: If you want to add two integers then, + operator is used. But, for user-defined types(like: objects), you can define the meaning of operator, i.e, you can redefine the way that operator works. For example: If there are two objects of a class that contain string as its data member, you can use + operator to concatenate two strings. Suppose, instead of strings if that class contains integer data member, then you can use + operator to add integers. This feature in C++ programming that allows programmer to redefine the meaning of operator when they operate on class objects is known as operator overloading.

Why Operator overloading is used in C++ programming?

You can write any C++ program without the knowledge of operator overloading. But, operator operating are profoundly used by programmer to make a program clearer. For example: you can replace the code like: calculation = add(mult(a,b),div(a,b)); with calculation = a*b+a/b;which is more readable and easy to understand.

How to overload operators in C++ programming?

To overload a operator, a operator function is defined inside a class as:
Operator function inside class in C++ programming
The return type comes first which is followed by keyword operator, followed by operator sign,i.e., the operator you want to overload like: +, <, ++ etc. and finally the arguments is passed. Then, inside the body of you want perform the task you want when this operator function is called.
This operator function is called when, the operator(sign) operates on the object of that class class_name.

Example of operator overloading in C++ Programming


/* Simple example to demonstrate the working of operator overloading*/
#include <iostream>
using namespace std;
class temp
{
   private:
      int count;
   public:
       temp():count(5){  }
       void operator ++() { 
        count=count+1; 
       }
       void Display() { cout<<"Count: "<<count; }
};
int main()
{
    temp t;
    ++t;        /* operator function void operator ++() is called */
    t.Display();
    return 0;
}
Output

Count: 6
Explanation
In this program, a operator function void operator ++ () is defined(inside class temp), which is invoked when ++ operator operates on the object of type temp. This function will increase the value of count by 1.

Things to remember while using Operator overloading in C++ language

  1. Operator overloading cannot be used to change the way operator works on built-in types. Operator overloading only allows to redefine the meaning of operator for user-defined types.
  2. There are two operators assignment operator(=) and address operator(&) which does not need to be overloaded. Because these two operators are already overloaded in C++ library. For example: Ifobj1 and obj2 are two objects of same class then, you can use code obj1=obj2; without overloading = operator. This code will copy the contents object of obj2 to obj1. Similarly, you can use address operator directly without overloading which will return the address of object in memory.
  3. Operator overloading cannot change the precedence of operators and associativity of operators. But, if you want to change the order of evaluation, parenthesis should be used.
  4. Not all operators in C++ language can be overloaded. The operators that cannot be overloaded in C++ are ::(scope resolution), .(member selection), .*(member selection through pointer to function) and ?:(ternary operator).

Following best practice while using operator overloading

Operator overloading allows programmer to define operator the way they want but, there is a pitfall if operator overloading is not used properly. In above example, you have seen ++ operator operates on object to increase the value of count by 1. But, the value is increased by 1 because, we have used the code:
void operator ++() { 
        count=count+1; 
       }
If the code below was used instead, then the value of count will be decreased by 100 if ++ operates on object.
void operator ++() { 
        count=count-100; 
       }
But, it does not make any sense to decrease count by 100 when ++ operator is used. Instead of making code readable this makes code obscure and confusing. And, it is the job of the programmer to use operator overloading properly and in consistent manner.
Again, the above example is increase count by 1 is not complete. This program is incomplete in sense that, you cannot use code like:
t1=++t
It is because the return type of operator function is void. It is generally better to make operator work in similar way it works with basic types if possible.
Here, are the examples of operator overloading on different types of operators in C++ language in best possible ways:

Increment ++ and Decrement -- Operator Overloading in C++ Programming

In this tutorial, increment ++ and decrements -- operator are overloaded in best possible way, i.e., increase the value of a data member by 1 if ++ operator operates on an object and decrease value of data member by 1 if -- operator is used.

Increment Operator Overloading


/* C++ program to demonstrate the overloading of ++ operator. */

#include <iostream>
using namespace std;
class Check
{
    private:
       int i;
    public:
       Check(): i(0) {  }
       void operator ++() 
          { ++i; }
       void Display() 
          { cout<<"i="<<i<<endl; }
};
int main()
{
    Check obj;

 /* Displays the value of data member i for object obj */
    obj.Display();

/* Invokes operator function void operator ++( ) */
    ++obj; 
  
/* Displays the value of data member i for object obj */
    obj.Display();  
    return 0;
}
Output
i=0
i=1
Explanation
Initially when the object obj is declared, the value of data member i for object obj is 0( constructor initializes i to 0). When ++ operator is operated on obj, operator function void operator++( ) is invoked which increases the value of data member i to 1.
This program is not complete in the sense that, you cannot used code:
obj1=++obj;
It is because the return type of operator function in above program is void. Here is the little modification of above program so that you can use code obj1=++obj.
/* C++ program to demonstrate the working of ++ operator overlading. */

#include <iostream>
using namespace std;
class Check
{
  private:
    int i;
  public:
    Check(): i(0) {  }
    Check operator ++() /* Notice, return type Check*/
    {
       Check temp;  /* Temporary object check created */
       ++i;         /* i increased by 1. */
       temp.i=i;   /* i of object temp is given same value as i */
       return temp; /* Returning object temp */
    }
   void Display()
      { cout<<"i="<<i<<endl; }
};
int main()
{
    Check obj, obj1;
    obj.Display();
    obj1.Display();
    obj1=++obj;
    obj.Display();
    obj1.Display();
    return 0;
}
Output
i=0
i=0
i=1
i=1
This program is similar to above program. The only difference is that, the return type of operator function is Check in this case which allows to use both codes ++obj; obj1=++obj;. It is because,temp returned from operator function is stored in object obj. Since, the return type of operator function is Check, you can also assign the value of obj to another object. Notice that, = (assignment operator) does not need to be overloaded because this operator is already overloaded in C++ library.

Operator Overloading of Postfix Operator

Overloading of increment operator up to this point is only true if it is used in prefix form. This is the modification of above program to make this work both for prefix form and postfix form.
/* C++ program to demonstrate the working of ++ operator overlading. */

#include <iostream>
using namespace std;
class Check
{
  private:
    int i;
  public:
    Check(): i(0) {  }
    Check operator ++ ()
    {
        Check temp;
        temp.i=++i;
        return temp;
    }

/* Notice int inside barcket which indicates postfix increment. */
    Check operator ++ (int)
    {
        Check temp;
        temp.i=i++;
        return temp;
    }
   void Display()
      { cout<<"i="<<i<<endl; }
};
int main()
{
    Check obj, obj1;    
    obj.Display(); 
    obj1.Display();
    obj1=++obj;     /* Operator function is called then only value of obj is assigned to obj1. */
    obj.Display();
    obj1.Display();
    obj1=obj++;     /* Assigns value of obj to obj1++ then only operator function is called. */
    obj.Display();
    obj1.Display();
    return 0;
}
Output
i=0
i=0
i=1
i=1
i=2
i=1
When increment operator is overloaded in prefix form; Check operator ++ () is called but, when increment operator is overloaded in postfix form; Check operator ++ (int) is invoked. Notice, theint inside bracket. This int gives information to the compiler that it is the postfix version of operator. Don't confuse this int doesn't indicate integer.

Operator Overloading of Decrement -- Operator

Decrement operator can be overloaded in similar way as increment operator. Also, unary operators like: !, ~ etc can be overloaded in similar manner.

C++ Program to Subtract Complex Number Using Operator Overloading

In this tutorial, subtraction - operator is overloaded to perform subtraction of a complex number from another complex number. Since - is a binary operator( operator that operates on two operands ), one of the operands should be passed as argument to the operator function and the rest process is similar to the overloading of unary operators.

Binary Operator Overloading to Subtract Complex Number


/* C++ program to demonstrate the overloading of binary operator by subtracting one complex number from another. */

#include <iostream>
using namespace std;
class Complex
{
    private:
      float real;
      float imag;
    public:
       Complex(): real(0), imag(0){ }
       void input()
       {
           cout<<"Enter real and imaginary parts respectively: ";
           cin>>real;
           cin>>imag;
       }
       Complex operator - (Complex c2)    /* Operator Function */
       {
           Complex temp;
           temp.real=real-c2.real;
           temp.imag=imag-c2.imag;
           return temp;
       }
       void output()
       {
           if(imag<0)
               cout<<"Output Complex number: "<<real<<imag<<"i";
           else
               cout<<"Output Complex number: "<<real<<"+"<<imag<<"i";
       }
};
int main()
{
    Complex c1, c2, result;
    cout<<"Enter first complex number:\n";
    c1.input();
    cout<<"Enter second complex number:\n";
    c2.input();
/* In case of operator overloading of binary operators in C++ programming, the object on right hand side of operator is always assumed as argument by compiler. */    
    result=c1-c2; /* c2 is furnised as an argument to the operator function. */
    result.output();
    return 0;
}
Explanation
In this program, three objects of type Complex is created and user is asked to enter the real and imaginary parts for two complex numbers which is stored in objects c1 and c2. Then statementresult=c1-c2 is executed. This statement invokes the operator function Complex operator - (Complex c2). When result=c1-c2 is executed, c2 is passed as argument to the operator function.In case of operator overloading of binary operators in C++ programming, the object on right hand side of operator is always assumed as argument by compiler. Then, this function returns the resultant complex number(object) to main() function and then, it is displayed.
Though, this tutorial contains the overloading of - operators, binary operators in C++ programming like: +, *, <, += etc. can be overloaded in similar manner.

No comments:

Post a Comment