Binary operator overloading

1,206 views 10 slides Apr 27, 2020
Slide 1
Slide 1 of 10
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10

About This Presentation

Introduction of operator overloading,syntax, Rules and Binary operator overloading with example


Slide Content

G.BALAJI MCA, M.Tech.,
Assistant Professor of Computer Science
Vivekananda College, Madurai

Operator Overloading:
Operator–Itisasymbolthatindicatesanoperation.
Arithmeticoperatorsare+(addtwonumbers),-(subtracttwo
numbers),*(Multiplytwonumbers),/(Dividebetweentwo
numbers).
At now, we will take an Addition ‘+’ Sign, its use of ‘+’ sign
is
5+5=10
2.5+2.5=5

OperatorOverloadingmeansmultiplefunctionsormultiple
jobs.Inoperatoroverloadingthe‘+’signuseofaddthetwo
objects.
OneofC++’sgreatfeaturesisitsextensibility,Operator
Overloadingismajorfunctionalityrelatedtoextensibility.
InC++,mostofoperatorscanbeoverloadedsothattheycan
performspecialoperationsrelativetotheclassesyoucreate.

ForExample,‘+’operatorcanbeoverloadedtoperforman
operationofstringconcatenationalongwithitspre-defined
jobofaddingtwonumericvalues.
Whenanoperatorisoverloaded,noneofitsoriginalmeaning
willbelost.
Afteroverloadingtheappropriateoperators,youcanuse
C++’sbuiltindatatypes.

Unary Operator
-Operators attached to a single operand.
(-a, +a, --a, ++a, a--, a++)
Binary Operator
-Operators attached to two operand.
(a-b, a+b, a*b, a/b, a%b, a>b, a<b )

return-type class-name:: operator op(arg-list)
{
function body
}
EXPLANATION
returntype–Itisthetypeofvaluereturnedbythespecified
operation.
op-Itistheoperatorbeingoverloaded.Itmaybeunaryor
binaryoperator.Itisprecededbythekeywordoperator.
operatorop-Itisthefunctionname,Whereoperatorisa
keyword.

INTRODUCTION
In Binary operator overloading function, there should be one
argument to be passed.
It is overloading of an operator operating on two operands.

#include<iostream>
class multiply
{
intfirst,second;
public:
void getdata(inta,intb)
{
first=a;
second=b;
}
Contd...,

void display()
{
cout<<“first=“<<first<<“second=“<<secon<<endl;
}
multiply operator *(multiply c);
};
void multiply::operator *(multiply c)
{
multiply temp;
temp.first=first*c.first;
temp.second=second*c.second;
return temp;
}
Contd..,

intmain()
{
multiply obj1,obj2,obj3;
obj1.getdata(15,20);
obj2.getdata(3,45);
obj3=obj1*obj2;
obj3.display();
return 0;
}
Output:
45
900
Tags