Explanation of Operator Overloading in Cpp
Explanation of Operator Overloading in Cpp
numbers.
#include <iostream>
#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.
class Complex {
private:
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;
Complex res;
return res;
void print() { cout << real << " + i" << imag << '\n'; }
This function prints the complex number in the form real + i imag.
7. Main Function
int main() {
8. Creating Objects
Complex c1(10, 5), c2(2, 4);
c1 is initialized as 10 + i5.
c2 is initialized as 2 + i4.
Complex c3 = c1 + c2;
c3.print();
o real part: 10 + 2 = 12
o imaginary part: 5 + 4 = 9
Final Output
12 + i9
Key Concepts: