Operator overloading
Operator overloading
types (classes and structs). This can make code involving custom types more intuitive and
readable.
1. Syntax: Operators are overloaded using the operator keyword followed by the
operator symbol.
2. Member Function or Friend Function: Operators can be overloaded as member
functions or as non-member (often friend) functions.
3. Preserve Operator's Original Meaning: It’s a good practice to keep the semantic
meaning of the operator similar to its original intent.
4. Cannot Overload Certain Operators: Operators like ::, .:, .*, sizeof, typeid, and
? : cannot be overloaded.
5. Custom Behavior: Operator overloading allows you to define custom behavior for
operators when applied to objects of your class.
1. Arithmetic Operators: +, -, *, /, %
2. Relational Operators: ==, !=, <, >, <=, >=
3. Logical Operators: &&, ||, !
4. Bitwise Operators: &, |, ^, ~, <<, >>
5. Increment/Decrement Operators: ++, --
6. Assignment Operators: =, +=, -=, *=, /=, %= etc.
7. Subscript Operator: []
8. Function Call Operator: ()
9. Dereference Operator: *
10. Member Access Operators: ->, .
Member Function:
Non-Member Function:
ReturnType operator OpSymbol (const ClassName& obj1, const ClassName&
obj2) {
// Implementation
}
Let's create a class Complex and overload the + operator to add two complex numbers.
Step-by-Step Example
Define the Class:
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
int main() {
Complex c1(3.0, 4.0);
Complex c2(1.0, 2.0);
Complex c3 = c1 + c2; // Using the overloaded + operator
return 0;
}
1.
Explanation:
● The Complex class represents complex numbers with real and imaginary parts.
● The operator+ function is defined as a member function to overload the + operator. It
takes a const Complex& as a parameter and returns a new Complex object that
represents the sum of the two complex numbers.
● The display function is used to print the complex number.
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
int main() {
Complex c1(3.0, 4.0);
Complex c2(1.0, 2.0);
Complex c3 = c1 + c2; // Using the overloaded + operator
Complex c4(4.0, 6.0);
if (c3 == c4) {
cout << "c3 is equal to c4" << endl;
} else {
cout << "c3 is not equal to c4" << endl;
}
return 0;
}
Explanation:
1. Consistency: The overloaded operator should behave in a way consistent with its usual
meaning. For example, + should perform addition, == should compare for equality, etc.
2. Symmetry: Ensure that the operations are commutative when appropriate (e.g., a + b
should be the same as b + a if it makes sense for your data type).
3. Efficiency: Overloaded operators should be implemented efficiently to avoid
unnecessary performance overhead.
4. Error Handling: Ensure that the overloaded operators handle errors and edge cases
gracefully.