9 Operator Overloading
9 Operator Overloading
9. Operator Overloading
Operator functions are implicit for predefined operators of built-in types and can not be
redefined
Operator functions/methods can be defined for struct and union types as well
Operator functions can be defined for enum type too
At least one argument of an operator function must be of a user-defined type (struct, class,
union, enum), or a reference to one.
Operator Overloading
#include<iostream> Complex operator*(Complex c1, int num) {
cout << "Inside friend function" << endl;
using std::cout; Complex result;
using std::endl; result.re = c1.re * num;
result.im = c1.im * num;
class Complex { return result;
double re, im; }
public:
Complex(double re = 0, double im = 0) { int main() {
this->re = re; Complex c1(1.1, 1.1), c2(2.2, 2.2), c3, c4;
this->im = im; c3 = c1 + c2;
} c4 = c3 * 2;
void print() { c3.print();
cout << re << " + j" << im << endl; c4.print();
} return 0;
Complex operator+(Complex &c) { }
cout << "Inside method" << endl;
Complex result; Inside method
result.re = this->re + c.re;
result.im = this->im + c.im; Inside friend function
return result; 3.3 + j3.3
} 6.6 + j6.6
friend Complex operator*(Complex c1, int num);
};
Operator functions/methods can be defined for two operands of different types too
Parameters can be passed by value or reference to the operator functions/methods
Operator Overloading
Only existing operators could be overloaded. We can not create new operators of our own
(e.g. **, <>)
Intrinsic properties of overloaded operators can not be changed
Preserves arity (number of operands it takes)
Preserves precedence
Preserves associativity
Both unary prefix and postfix could be oveloaded
void class_name::operator++() // prefix
void class_name::operator++(int) // postfix, int is used to distinguish it from prefix
Like overload of other operators, they can also return value and could be overloaded
using functions
Some operators could not be overloaded
:: . .* sizeof ?:
Operators && || and , could be overloaded but they lose their special properties: short-
circuit evaluation and sequencing (they will not be a sequence point for new types)
#include<iostream> Complex Complex::operator*(int num) {
cout << "Inside method II" << endl;
using std::cout; return Complex(this->re * num, this->im * num);
using std::endl; }