Operator Overloading
Operator Overloading
2
OPERATOR OVERLOADING RESTRICTIONS
🞆You cannot overload
⚫ :: (scope resolution)
⚫ . (member selection)
⚫ .* (member selection through pointer to function)
⚫ ? (ternary conditional) operators
🞆Overloading cannot change the original precedence of the operator
🞆The number of operands on which the operator would be applicable cannot be
changed too
🞆Operator functions cannot have default arguments
3
OPERATOR OVERLOADING GENERAL FORM
🞆Prototype definition
class class-name{
……..
return-type operator # (arg-list);
};
🞆Function definition
return-type class-name :: operator # (arg-list){
//operation to be performed
}
4
OVERLOADING BINARY OPERATORS
class coord {
int x, y;
public:
coord(int a = 0, int b = 0) {
x = a; y = b;
}
void show() {
cout << x << “, ” << y << endl;
}
coord operator+(coord obj);
coord operator+(int i);
coord operator-(coord obj);
5
coord operator=(coord obj);
};
OVERLOADING BINARY OPERATORS
coord coord::operator+(coord obj) {
coord temp;
temp.x = x + obj.x;
temp.y = y + obj.y;
return temp;
}
coord coord::operator+(int i) {
coord temp;
temp.x = x + i;
temp.y = y + i;
return temp; 6
}
OVERLOADING BINARY OPERATORS
coord coord::operator-(coord obj) {
coord temp;
temp.x = x - obj.x;
temp.y = y - obj.y;
return temp;
}
coord coord::operator=(coord obj) {
x = obj.x;
y = obj.y;
return *this;
} 7
OVERLOADING BINARY OPERATORS
void main() { coord c6 = c1 + c2 + c3;
coord c1(20, 20), c2(10, 10); // (c1.+(c2)).+(c3)
coord c3 = c1 + c2; // c1.+(c2) c6.show(); // 60, 60
c3.show(); // 30, 30 (c6 – c4).show(); // 25, 25
};
OVERLOADING A UNARY OPERATOR
coord coord::operator++() {
++x; ++y; return *this;
} // prefix version
coord coord::operator-() {
coord temp;
temp.x = -x; temp.y = -y;
return temp;
}
coord c5 = -c1;
🞆Postfix increment
// c1.-() 🞆coord operator++(int unused);
c1.show(); // 11, 11
c5.show(); // -11, -11
11
Acknowledgement
http://faizulbari.buet.ac.bd/Courses.html
http://mhkabir.buet.ac.bd/cse201/index.html
THE END
Topic Covered: Chapter 6