NU-Lec 12 - Operator Overloading - I
NU-Lec 12 - Operator Overloading - I
Lecture No. 12
Operator Overloading
Introduction
• The variables of native data types can perform a
number of different operations (functions) using
operators ( +, - , / , *)
– Example: a + b * c
– Example: if ( a < b )
class complex { /* … */ };
complex a(2,1), b(3,0);
…
cout << a + b << a*b << -b;
cout << (a != b);
Introduction
• With the help of operator overloading
we can add operator functionality in the
class’s objects
• Example: operator/
– a = 14.0 / 2; (one float and one int argument)
– a = 14.0 / 2.0; (two float arguments)
– a = 14 / 2; (two ints, INTEGER DIVISION)
• Example
int i, j;
double d, e;
i + j; /* add two int */
i + d; /* add an int and a double */
Operator Overloading Syntax
• a = b + c;
• datatype operator+ (datatype)
double sum;
Employee Clerk (111, 10000), Driver (222, 6000);
sum = Clerk.addTwo(Driver);
sum = Clerk.operator+(Driver);
void main()
{
Employee Clerk(115, 20000.00);
Employee Driver(256, 15500.55);
Employee Secretary(567, 34200.00);
double sum;
void main()
{
Employee Clerk(115, 20000.00);
Employee Driver(256, 15500.55);
Employee Secretary(567, 34200.00);
Employee sum(0, 0.0);
}
29
Reading References