class Imaginary
{
private:
double real, imag;
public:
Imaginary(double r, double i) : real(r), imag(i) {}
Imaginary operator+(const Imaginary& other)
{
return Imaginary(real + other.real, imag + other.imag);
}
};
How it works
When the program writes:
num1 + num2
C++ actually calls:
num1.operator+(num2)
Advantages
Easier for beginners
Cleaner class design
Direct access to private data
More intuitive for object-oriented programming
Limitation
The left operand must be an object of the class.
Example that works:
num1 + num2
Example that does NOT work easily:
5 + num1
because 5 is not an Imaginary object.