Examples of Operator Overloading in c++

Example 1: Overloading the + operator for custom class objects:

#include <iostream>

class Complex {
public:
int real;
int imaginary;

Complex(int r, int i) : real(r), imaginary(i) {}

Complex operator+(const Complex& other) {
Complex result(real + other.real, imaginary + other.imaginary);
return result;
}
};

int main() {
Complex num1(3, 4);
Complex num2(1, 2);
Complex sum = num1 + num2;

std::cout << “Sum: ” << sum.real << ” + ” << sum.imaginary << “i” << std::endl;
return 0;
}

Note: This example overloads the + operator to perform addition for Complex objects.

 

Example 2: Overloading the << operator for custom class objects to enable custom output:

#include <iostream>

class MyString {
public:
std::string str;

MyString(const std::string& s) : str(s) {}

friend std::ostream& operator<<(std::ostream& out, const MyString& myStr) {
out << myStr.str;
return out;
}
};

int main() {
MyString myStr(“Hello, Operator Overloading!”);
std::cout << myStr << std::endl;
return 0;
}

Note: Here, the << operator is overloaded to allow custom output for MyString objects

Top online courses in Teaching & Academics

Related Posts

Leave a Reply