by Dinesh Thakur Category: Classes in C++

A feature of some programming languages in which the same 0PERATORmay be used on different data types with different, but analogous, results. For example most languages permit the same operator + to add either INTEGER or FLOATING-POINT numbers, and many further allow it to be used to CONCATENATE strings, so that 'rag' + 'mop' produces 'ragmop'. A few languages, including C++, allow the programmer to create new operator overloading.

#include <iostream.h>

#include<conio.h>
class Values
{
      int a,b;
      public:
     Values(){}
                  Values(int aa,int bb)
               {
                      a=aa;
                      b=bb;
               }
                   void show()
               {
                   cout <<a<<" ";
                   cout <<b<<"\n";
                }
                   friend Values operator+(Values p1 ,Values p2); //friend
                   Values operator-(Values p2);
                   Values operator=(Values p2);
                   Values operator++();
};
 //Now,+is overloaded using friend function.
             Values operator+(Values p1 ,Values p2)
         {
               Values temp;
               temp.a =p1.a +p2.a;
               temp.b =p1.b +p2.b;
               return temp;
         }
              Values Values::operator-(Values p2)
         {
              Values temp;
               temp.a =a +p2.b;
               temp.b =a +p2.b;
               return temp;
          }
              Values Values::operator=(Values p2)
         {
               a =p2.a;
               b =p2.a;
               return *this;
          }
              Values Values::operator++()
         {
              a++;
              b++;
              return *this;
          }
              void main()
          {
               clrscr();
               Values v1 (20,30),v2(15,40);
               v1.show();
               v2.show();
               ++v1;
               v1.show();
               v2 =++v1 ;
               v1.show();
               v2.show();
               v1=v2;
               v1.show();
               v2.show();
               getch();
         }

Operator Overloading Using a Friend Function



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles