Operator Overloading
Operator Overloading
Interpreted as:
Unary operators : operator op(x) in case of
friend functions.
Binary operators : x.operator op(y) in case of
member functions.
operator op(x,y) in case of friend functions
enter number 25
number is 25 // entered number
number is -25 // negated number
int main()
{
point p3,p1(12,23),p2(21,32);
clrscr();
p1.show();
p2.show();
p3=p1+p2; // same as p3=p1.operator+(p2)
p3.show();
return 0;
}
cordinates are 12 23
cordinates are 21 32
cordinates are 33 55
enter number 25
number is 25 // entered number
number is -25 // negated number
number is 0 // result of 25-25
int main()
{ invent1 s1(100,5,140.0);
invent2 d1;
float total_value;
total_value=s1; /invent1 to float/
d1=s1 ; / invent1 to invent2 /
cout<<“Product details 1”;
s1.putdata();
cout<<“Stock value”<<total_value;
cout<<“Product details 2”;
d1.putdata();
return 0;
}
ANS 1,2,4
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 43
B. While defining an overloaded operator
1. Operator keyword must be included in
function definition
2. Any number and type of arguments can
be passes to the operator function
3. Operator can perform any function.
4. At least one of the arguments must be of
user defined data type.
ANS 2,3
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 45
D. Which is (are) false about operator
function?
1.Can be defined only as a member function
2.Can return only objects of built in data
types
3.Can be defined outside the class
4.Can take any type of arguments
5. Always takes one argument less than
required for that operator.
ANS 3 and 4
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 46
E. Which of the following can be overloaded
using friend function?
1. Assignment (=)
2. Unary minus(-) and subscript([])
3. Dot operator (.)
4. <= and ++
5. Scope resolution operator(:: )
ANS only 4