Operator Overloading in C++
In C++, operator overloading is done using the operator keyword followed by the symbol of the operator being overloaded. Here’s a simple example with a Complex class for complex numbers:
#include <iostream>
using namespace std;
class Complex {
public:
float real, imag;
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
// Overload + operator
Complex operator + (const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}
// Display method
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3.0, 4.0), c2(1.0, 2.0);
Complex c3 = c1 + c2; // Using overloaded +
c3.display(); // Output: 4.0 + 6.0i
return 0;
}
Output
4 + 6i
Operator Overloading in Programming
Operator Overloading is a feature in some programming languages used to redefine or “overload” the standard behavior of operators (such as +, -, *, etc.) to work with user-defined data types. This is useful when working with objects of custom classes. In this article, we will learn about the basics of Operator overloading and its implementation in different languages.
Table of Content
- What is Operator Overloading?
- Operator Overloading in C++
- Operator Overloading in Python
- Advantages of Operator Overloading
- Disadvantages of Operator Overloading