Basics of operator overloading
1. Overloading binary operators
2. Overloading the relational and logical operators
3. Overloading a unary operator
4. Using friend operator functions
5. A closer look at the assignment operator
6. Overloading the [ ]subscript operator
BASICS OF OPERATOR OVERLOADING
1.Allows the programmer to define the meaning of
the C++ operators relative to programmer
defined classes
2. Resembles function overloading
3. An operator is always overloaded relative to a
user-defined type, such as a class
4.When overloaded, the operator loses none of its
original meaning
5. To overload an operator, we create an operator
function
6. An operator function can be
-A member of the class for which it is defined
-A friend of the class for which it is defined
General form of a member operator function
return-type class-name::operator#(arg-list) { … }
Restrictions:
The precedence of the operator cannot be changed
The number of operands that an operator takes cannot be altered
The following operators cannot be overloaded
. :: .* ? preprocessor operators
Except for the =, operator functions are inherited by
any derived class.
Operator functions can be further overloaded in the
derived classes.
Operator functions cannot have default arguments.
Running Codes
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);
coord operator=(coord obj);
};
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;
}
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;
}
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);
coord operator=(coord obj);
};
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;
}
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;
}