Operator Overloading - Kamills-12/2143-OOP GitHub Wiki
Operator overloading means giving custom meaning to operators (like +
, -
, ==
, etc.) when they’re used with objects.
Normally, +
adds numbers. But with operator overloading, you can make +
work for something like two ComplexNumber
objects or custom data types and define what “+” actually does in that context. Interesting.
#include <iostream>
using namespace std;
class Complex {
public:
float real, imag;
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
// OVERLOAD the '+' operator
Complex operator + (const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
void print() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 2);
Complex c2(1, 7);
Complex result = c1 + c2; // Calls our overloaded '+'
result.print(); // Output: 4 + 9i
return 0;
}