Operator Overloading - Rybd04/2143-OOP GitHub Wiki
Allows built-in operators like +,-,*,==, and others to work with objects. It involves redefining the behavior of operators.
A good example would be a function that only needs the plus sign to add fractions. Instead of calling fraction.add(3/4, 2/3) you would just write 3/4 + 2/3.
#include <iostream>
using namespace std;
class Complex {
public:
int real, imag;
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
// Overload the + operator
Complex operator + (const Complex &obj) {
Complex result;
result.real = real + obj.real;
result.imag = imag + obj.imag;
return result;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 4);
Complex c2(1, 2);
Complex c3 = c1 + c2; // Using overloaded +
c3.display();
return 0;
}
https://www.geeksforgeeks.org/operator-overloading-cpp/ https://www.programiz.com/cpp-programming/operator-overloading