Q3. Operator Overloading in C++
Question:
Write program to demonstrate use of operator overloading.
My Approach
Operator overloading ka use tab hota hai jab hum C++ ke operators (like +, -, ==, etc.) ko apne custom class objects ke liye redefine karna chahte hain.
Maine yaha ek real-time example liya hai: Complex Numbers Addition and Comparison.
Isme hum do complex numbers ka addition aur unka equality check == operator ke through karenge.
Program Code
File Name: operator_overloading.cpp
#include <iostream>
using namespace std;
class Complex {
private:
float real, imag;
public:
// Constructor
Complex(float r = 0, float i = 0) {
real = r;
imag = i;
}
// Overload + operator for addition
Complex operator+(const Complex &c) {
return Complex(real + c.real, imag + c.imag);
}
// Overload == operator for comparison
bool operator==(const Complex &c) {
return (real == c.real && imag == c.imag);
}
// Display function
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 2), c2(1, 7), c3;
cout << "Complex Number 1: ";
c1.display();
cout << "Complex Number 2: ";
c2.display();
// Using overloaded + operator
c3 = c1 + c2;
cout << "Result of Addition: ";
c3.display();
// Using overloaded == operator
if (c1 == c2) {
cout << "Both complex numbers are equal." << endl;
} else {
cout << "Complex numbers are not equal." << endl;
}
return 0;
}Sample Input / Output
Output:
Complex Number 1: 3 + 2i
Complex Number 2: 1 + 7i
Result of Addition: 4 + 9i
Complex numbers are not equal.Explanation
operator+overload kiya gaya taaki doComplexobjects ko directly+se add kiya ja sake.operator==overload kiya gaya jo check karta hai ki dono complex numbers equal hai ya nahi.- Ye program show karta hai ki operators ko objects ke liye customize karna possible hai.
Real Time Relevance
- Operator Overloading ka use real-world applications jaise Matrix operations, Complex numbers, Fractions, Vectors, Strings me hota hai.
- Ye code readability aur usability ko improve karta hai, jaise
a+binstead ofa.add(b).
Conclusion
Is program me humne dekha ki kaise operator overloading ke through custom objects (Complex Numbers) ke liye operators redefine kiye ja sakte hain.
Mujhe personally lagta hai ki jab bhi mathematical ya custom classes banani ho, operator overloading ek practical aur powerful concept hai.
Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live