C++ Binary Operator Overloading
C++ Overloaded Operators and Overloaded Functions
A binary operator requires two operands; the following is an example of a binary operator. The addition (+), subtraction (-), multiplication (*), and division (/) operators we normally use are all binary operators—just like the addition (+) operator.
The following example demonstrates how to overload the addition operator (+). Similarly, you can try overloading the subtraction (-) and division (/) operators.
Example
#include
<
iostream
using
namespace
std;
class
Box
{
double
length
;
// length
double
breadth
;
// width
double
height
;
// height
public
:
double
getVolume
(
void
)
{
return
length
breadth
height
;
}
void
setLength
(
double
len
)
{
length
=
len
;
}
void
setBreadth
(
double
bre
)
{
breadth
=
bre
;
}
void
setHeight
(
double
hei
)
{
height
=
hei
;
}
// overload + operator to add two Box objects
Box
operator
(
const
Box
&
b
)
{
Box
box
;
box
.
length
=
this
->
length
b
.
length
;
box
.
breadth
=
this
->
breadth
b
.
breadth
;
box
.
height
=
this
->
height
b
.
height
;
return
box
;
}
}
;
// main function of the program
int
main
(
)
{
Box
Box1
;
// declare Box1 of type Box
Box
Box2
;
// declare Box2 of type Box
Box
Box3
;
// declare Box3 of type Box
double
volume
=
0
.0
;
// store volume in this variable
// details of Box1
Box1
.
setLength
(
6
.0
)
;
Box1
.
setBreadth
(
7
.0
)
;
Box1
.
setHeight
(
5
.0
)
;
// details of Box2
Box2
.
setLength
(
12
.0
)
;
Box2
.
setBreadth
(
13
.0
)
;
Box2
.
setHeight
(
10
.0
)
;
// volume of Box1
volume
=
Box1
.
getVolume
(
)
;
cout
<<
"
Volume of Box1 :
"
<<
volume
<<
endl
;
// volume of Box2
volume
=
Box2
.
getVolume
(
)
;
cout
<<
"
Volume of Box2 :
"
<<
volume
<<
endl
;
// add the two objects to get Box3
Box3
=
Box1
Box2
;
// volume of Box3
volume
=
Box3
.
getVolume
(
)
;
cout
<<
"
Volume of Box3 :
"
<<
volume
<<
endl
;
return
0
;
}
When the code above is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400