Saturday, June 17, 2023

Operator overloading in CPP

 

C++ Overloading (Function and Operator)

If we create two or more members having the same name but different in number or type of parameter, it is known as C++ overloading. In C++, we can overload:

It is because these members have parameters only.

Operators that can be overloaded

Examples

Binary Arithmetic

+, -, *, /, %

Unary Arithmetic 

+, -, ++, —

Assignment

=, +=,*=, /=,-=, %=

Bitwise

& , | , << , >> , ~ , ^

De-referencing

(->)

Dynamic memory allocation,
De-allocation

New, delete 

Subscript

[ ]

Function call 

()

Logical 

&,  | |, !

Relational

>, < , = =, <=, >=

Overloadable/Non-overloadable Operators

The following operators can be overloaded -

+

-

*

/

%

^

&

|

~

!

,

=

< 

> 

<=

>=

++

--

<< 

>> 

==

!=

&&

||

+=

-=

/=

%=

^=

&=

|=

*=

<<=

>>=

[ ]

()

->

->*

new

new [ ]

delete

delete [ ]

Following operators can't be overloaded -

::

sizeof

?:

.

 

Types of overloading in C++ are:

  • Function overloading
  • Operator overloading


C++ Operator Overloading:

#include <iostream.h>

#include<conio.h>

class a

{

    private:

    int data;

    public:

    void getvalue()

    {

        cin>>data;

    }

    a operator+(a ob)

    {

        a t;

        t.data=data + ob.data;

        return t;

    }

    a operator- (a ob)

    {

    a t;

    t.data = data - ob.data;

    return t;

    }

a operator* (a ob)

    {

    a t;

    t.data = data * ob.data;

    return t;

    }

a operator/ (a ob)

    {

    a t;

    t.data = data / ob.data;

    return t;

    }

a operator<(a ob)

    {

    a t;

    t.data = data < ob.data;

    return t;

    }

a operator>(a ob)

    {

    a t;

    t.data = data > ob.data;

    return t;

    }

 

    int display()

    {

       

        return data;

       

    }

};

void  main()

{

 

    a obj1, obj2, sum, sub,mul,div,lt,gt;

    clrscr();

    cout<<"enter an integer value for obj1: ";

    obj1.getvalue();

    cout<<"Enter an integer value for obj2: ";

    obj2.getvalue();

    sum= obj1+obj2;

    sub=obj1-obj2;

    mul=obj1*obj2;

    div=obj1/obj2;

    lt=obj1<obj2;

    gt=obj1>obj2;

    cout<<"Addition result is = "<<sum.display()<<endl;

    cout<<"Subtraction result is = "<<sub.display()<<endl;

    cout<<"Multiplication result is ="<<mul.display()<<endl;

    cout<<"Division result is = "<<div.display()<<endl;

    cout<<"Less than result is = "<<lt.display()<<endl;

    cout<<"greater than result is = "<<gt.display()<<endl;

    getch();

   

}

output

 


0 comments:

Post a Comment