Download Our Beta Android App And Help Us Build Awesome Stuff!  Download Now.

LEARN Operator Overloading - 1

Category: Notes

Course: B.Tech.

Semester: 4

  1. We overloaded the unary operator, "-", to return the result as Data+5, instead of -Data .
  2. We overloaded the binary operator, "+", to return the result as Data1 * Data2, instead of Data1 + Data2 .
#include <iostream>
using namespace std ;

class data
{
    int A ;

    public :
        data( int a )
        {
            A = a ;
        }
        int operator - ( )
        {
            return (A + 5) ;
        }
        int operator + ( data D2 )
        {
            int result = A * D2.A ;
            return result ;
        }
};


int main()
{
    int check = 2;
    cout<< -check <<endl ;         //o/p => "-2" , as check is not the object of overloaded class. It works normally

    data D1(15), D2(10) ;

    cout<< -D1 <<endl ;           //o/p => "20"     (15+5)
    cout<< D1+D2 <<endl ;         //o/p => "150"    (15*10)

    return 0 ;
}

Added by StAn

Comments