Friday, 3 January 2014

Operator overloading

The ability to create new meaning to an existing operator is called operator overloading.Various operators involved in operator overloading are:

  • Mathematical operators like +,-,*,/,% 
  • Relational operators like <,>,<=,>=,!=
  • Logical operators like &&,||,!
  • Access operator  like [,],->
  • Assignment operator  =
  • Stream I/O operator <<,>>
Operators that can't be overloaded:
  1. Scope resolution operator
  2. Sizeof operator
  3. Conditional operator
  4. Dereference operator
Syntax for operator overloading:

Return_type class_name :: operator operator_to_be_overloaded(argument list)

Example: void sample::operator ++()
{
         //statement;
}

Operator overloading can be classified into two types:

  • Unary operator overloading
  • Binary operator overloading
Program for Unary operator overloading:
#include<iostream.h> 
          #include<conio.h>
         class sample
         {
              private:
                        int val1,val2;
              public:
                       sample(int x,int y);
                       void operator ++();
                       void operator ++ (int x);
                       void display();
         };
        sample::sample(int x,int y)
        {
              val1=x;
              val2=y;
        }
        void sample::operator ++()
        {
             val1++;
            val2++;
         }
         void sample::operator ++(int x)
        {
             val1++;
             val2++;
        }
        void sample::display()
       {
            cout<<"\n value1"<<val1;
            cout<<"\nvalue2"<<val2;
        }
        void main()
        {
            sample s(10,20);
            cout<<"\nbefore overloading";
            s.display();
           ++s;
           cout<<"after overloading prefix form";
           s.display();
          s++;
          cout<<"after overloading postfix form";
          s.display();
      }

No comments:

Post a Comment