Week4b Op Overloading
Week4b Op Overloading
For example, The + operator, when used with values of type int, returns their sum. However, when used
with objects of a user-defined type, it is an error.
In this case, we can define the behavior of the + operator to work with objects as well.
• The concept of defining operators to work with objects and structure variables is known as
operator overloading.
Rules and Limitations
Existing operators can only be overloaded, but the new operators cannot be overloaded.
eg. overloading +, -, *, /, <<, >> etc are allowed but creating a new operator like %%, ** etc not
allowed.
The overloaded operator contains atleast an operand of the user-defined data type. You cannot
overload an operator for primitive types like int or float alone.
eg. overloading “+” for adding two instances of a class is allowed but for adding int and float is not
allowed.
We cannot use friend function to overload certain operators. However, the member function can be
used to overload those operators.
eg. some operators, such as “=“, “()”, “[]” and “->” cannot be overloaded using friend functions.
Rules and Limitations
When unary operators are overloaded through a member function take no explicit arguments, but, if
they are overloaded by a friend function, takes one argument.
When binary operators are overloaded through a member function takes one explicit argument, and if
they are overloaded through a friend function takes two explicit.
Here,
• returnType – the return type of the function
• operator – a keyword
• symbol – the operator we want to overload (+, <, -, etc)
• arguments – the arguments passed to the function
Member Function Non Member Function
Syntax
Expression Syntax Definition Syntax Definition Syntax
Unary
Operator object_name returnType operator symbol(int) {} returnType operator symbol(returnType&
operator_symbol; parameter_name, int) {}
Note –
• The dummy int parameter differentiates postfix Note –
Postfix from prefix. • Takes an object by reference.
• Returns a copy of the original object. • Uses a dummy int parameter to
differentiate from prefix.
• Returns a copy of the original object
(before modification).
Member Function Non Member Function
Syntax
Expression Syntax Definition Syntax Definition Syntax
// Postfix increment
Counter operator++(Counter& c, int) {
Counter temp = c; // Store old value
++c.value; // Modify original object
return temp; // Return old state
}
Overloading binary ‘+’ through a member function
#include <iostream> int main() {
using namespace std; Complex c1(3, 4), c2(1, 2);
Complex sum = c1 + c2; // Calls operator+
class Complex {
private: sum.display(); // Output: 4 + 6i
double real, imag; }
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}