Thursday, April 4, 2013

Operator overloading I – C++



Operator overloading is a form of function overloading. Operator overloading known as operator improvised form of polymorphism. The function overloading allows the programmer to use different functions with different argument list that is not identical, whereas   operator overloading lets the programmer define different account of an operator for use with different operand types.

Some of the operators which can use in operator overloading
Operator
Description
+   -   *   /    %
Arithmetic Operators
++  --
Prefix & Postfix Increment and decrements
&&   ||   !  ~
Logical Operator
&  |  ^  <<  >>
Bitwise Operator
=  *=  /=  %=   +=  -=
<<=    >>=    &=    ^=  |=
Assignment Operators
==  <=   >=

Relational Operator
[]
Array subscript operator

Following Operators cannot be use in operator overloading
.
.*
::
?:


Example :

#include <iostream.h>

//Example of Operator + - * / %

  class opAr
      {
           private:
              int n;
           public:
              opAr()
                   {
                        n=0;
                   }
               void input();
              void disp();
              opAr operator +(opAr);
              opAr operator -(opAr);
              opAr operator /(opAr);
              opAr operator *(opAr);
              opAr operator %(opAr);
      };
  void opAr::input()
      {
           cout<<"\n\tEnter no : ";
           cin>>n;
      }
  void opAr::disp()
      {
           cout<<" "<<n;
      }
  opAr opAr::operator +(opAr O)
      {
           opAr O1;
           O1.n=n+O.n;
           return O1;
      }
  opAr opAr::operator -(opAr O)
      {
           opAr O1;
           O1.n=n-O.n;
           return O1;
      }
  opAr opAr::operator *(opAr O)
      {
           opAr O1;
           O1.n=n*O.n;
           return O1;
      }
  opAr opAr::operator /(opAr O)
      {
           opAr O1;
           O1.n=n/O.n;
           return O1;
      }

  opAr opAr::operator %(opAr O)
      {
           opAr O1;
           O1.n=n%O.n;
           return O1;
      }

  int main()
      {
           opAr O1,O2,O3;
           O1.input();
           O2.input();
           cout<<"\n\tNos. ";
           O1.disp();
           cout<<"  &  ";
           O2.disp();
           cout<<"\n\tResult ==>>  ";
           cout<<"\n\n\t +   ";
           O3=O1+O2;
           O3.disp();
           cout<<"\n\t -   ";
           O3=O1-O2;
           O3.disp();
           cout<<"\n\t *   ";
           O3=O1*O2;
           O3.disp();
           cout<<"\n\t /   ";
           O3=O1/O2;
           O3.disp();
           cout<<"\n\t %   ";
           O3=O1%O2;
           O3.disp();
           return 0;
      }




No comments: