This C++ program demonstrates operator overloading using the + operator for adding two complex
numbers.
Breaking Down the Code:
1. Header Files & Namespace
#include <iostream>
using namespace std;
#include <iostream>: This includes the input-output stream library for using cout and cin.
using namespace std; : This allows direct use of cout and cin without writing std:: every time.
2. Creating a Class Complex
class Complex {
We define a class Complex to represent complex numbers.
3. Private Data Members
private:
int real, imag;
real and imag store the real and imaginary parts of a complex number.
4. Constructor
public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
This is a constructor that initializes real and imag.
It takes two parameters (r and i) and assigns them to real and imag.
If no values are provided, both default to 0.
5. Overloading the + Operator
Complex operator+(Complex const& obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
Purpose: This function allows us to add two Complex numbers using +.
Complex operator+(Complex const& obj): Defines the + operator.
res.real = real + obj.real; → Adds the real parts.
res.imag = imag + obj.imag; → Adds the imaginary parts.
return res; → Returns the new complex number.
6. Printing the Complex Number
void print() { cout << real << " + i" << imag << '\n'; }
This function prints the complex number in the form real + i imag.
7. Main Function
int main() {
The main function starts program execution.
8. Creating Objects
Complex c1(10, 5), c2(2, 4);
c1 is initialized as 10 + i5.
c2 is initialized as 2 + i4.
9. Adding Two Complex Numbers
Complex c3 = c1 + c2;
c3 stores the result of c1 + c2.
The + operator calls our overloaded function.
10. Printing the Result
c3.print();
This prints 12 + i9 since:
o real part: 10 + 2 = 12
o imaginary part: 5 + 4 = 9
Final Output
12 + i9
Key Concepts:
✅ Operator Overloading: We redefine + for Complex objects.
✅ Encapsulation: The data is private and accessed via class methods.
✅ Constructor Usage: Helps initialize complex numbers easily.