Operator Overloading in CPP
Operator Overloading in CPP
return 0;
}
Relational Operators
• Operators: ==, >=, <=, !=
• Used to compare objects.
• Example: Overloading '==' to compare two
objects.
Example
#include <iostream>
using namespace std;
int main() {
Complex c1(4, 5), c2(4, 5), c3(2, 3);
class Complex {
int real, imag;
cout << "c1: ";
public:
// Constructor c1.display();
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
cout << "c2: ";
// Overload == operator c2.display();
bool operator==(const Complex &obj) const {
return (this->real == obj.real && this->imag == obj.imag); cout << "c3: ";
}
c3.display();
// Overload != operator
bool operator!=(const Complex &obj) const {
return (this->real != obj.real || this->imag != obj.imag); // Comparison examples
}
cout << "\nIs c1 == c2? " << (c1 == c2 ? "Yes" :
// Overload >= operator (compares magnitude) "No") << endl;
bool operator>=(const Complex &obj) const {
return (real >= obj.real );
cout << "Is c1 != c3? " << (c1 != c3 ? "Yes" : "No")
} << endl;
// Overload <= operator cout << "Is c1 >= c3? " << (c1 >= c3 ? "Yes" : "No")
bool operator<=(const Complex &obj) const { << endl;
return (real <= obj.real);
} cout << "Is c3 <= c1? " << (c3 <= c1 ? "Yes" : "No")
<< endl;
// Display function
void display() const {
}
cout << real << " + " << imag << "i" << endl;
return 0;
}; }
Unary Operators
• Operators: ++, --
• Overloaded to modify object states or return
computed values.
• Example: Overloading '++' to increment an
object's value.
Example
#include <iostream> int main() {
using namespace std;
Complex c1(5, 6), c2(3, 4), c3;
class Complex {
int real, imag; cout << "Initial c1: ";
c1.display();
public: cout << "Initial c2: ";
// Constructor
c2.display();
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
// Overload post-decrement --
// Overloaded -- operators
Complex operator--(int) { cout << "\nPre-decrement c2: ";
Complex temp = *this; --c2;
real--; c2.display();
imag--;
return temp;
} cout << "Post-decrement c2: ";
c2--;
// Display function c2.display();
void display() const { system("pause");
cout << real << " + " << imag << "i" << endl;
return 0;
}
}; }
Stream Insertion and Extraction
• Operators: <<, >>
• Used to input and output user-defined
objects.
• Example: Overloading '<<' to display object
details.
Example: Stream Operators
#include<iostream>
using namespace std; int main()
{
class Complex { Complex c1, c2(2, 'i');
int real; cin >> c1;
char imag;
cout << c1 <<endl;
public:
Complex() {
real = 0; cout << c2;
imag = 'i';
} system("pause");
Complex(int r, char i) : real(r), imag(i) {} return 0;
// Overload >> (stream extraction operator) for input }
friend istream& operator>>(istream& in, Complex& c) {
cout << "Enter real part: ";
in >> c.real;
cout << "Enter imaginary part: ";
in >> c.imag;
return in; // Allow chaining
}