Operator Overloading Uta018
Operator Overloading Uta018
Distance operator+(Distance& d) {
Distance d3;
//.. set d3
return d3;
}
Unary operator
Operators that act upon a single operand to produce a new
value. For example:
• unary minus(-)
• increment(++)
Overloading unary ‘-’ operator
Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches); // or return *this;
}
Binary operator
• Operators that works with two operands are binary
operators. For example:
a) Arithmatic (+ , – , * , /)
b) Relational (== or <= etc)
c) Logical (&& or || etc.)
d) Bitwise (&, | etc.)
Overloading binary ‘+’ operator
int main(){
Time t1(5,15,34),t2(9,53,58),t3;
t3 = t1 + t2; t3.show();
}
Hint:
Time Time::operator+(Time t1) {
Time t;
int a,b;
a = s+t1.s;
t.s = a%60; b = (a/60)+m+t1.m;
t.m = b%60; t.h = (b/60)+h+t1.h;
t.h = t.h%12;
return t;
}
Overloading relational operator
Example of overloading < operator in the Distance class
class Test {
private: //….
public:
Test ( data_type) { // conversion code }
};
class Cel{
float c;
public:
Cel(){c=0;}
Cel(float f){c=(f-32)* 5/9;}
void show(){cout<<"Celsius: "<<c;}
};
int main(){
Cel cvalue(50);
float f;
cout<<“Fahrenheit : "; cin>>f;
cvalue=f; //conversion
cvalue.show();
}
UDT to basic type
• Done by overloading the cast operator of basic type as a
member function.
class Test{
public:
operator data_type() { //Conversion code }
};
class Celsius{
float temper;
public:
//…
operator float(){
float fer = temper *9/5 + 32;
return fer;
}
//…
};
int main(){
Celsius cel; // finish code by setter & getter
float fer=cel; // UDT to basic type
cout<<fer;
}
One UDT to another UDT
• This conversion is exactly like conversion of UDT to basic type
i.e. overloading the cast operator is used. For example
ClassA objA;
ClassB objB = objA;
int main() {
Test t1; t1.show();
t1 = t1(15); t1.show();
}
Error
[Error] no match for call to '(Test) (int)'
What will class Test {
int i;
be the public:
output? Test() {i=0;}
Test operator()(int a) { return *this; }
void show() {cout << i << endl;}
};
int main() {
Test t1; t1.show();
t1 = t1(15); t1.show();
}
It will work
0
0