fbpx

Types of Operator Overloading in C++

Types of Operator Overloading

INTRODUCTION

Operator overloading in C++ enhances code readability and flexibility by allowing developers to redefine how operators behave for user-defined types. This feature empowers classes to handle operations intuitively, similar to built-in data types, making code easier to write and maintain.

There are two main types of operator overloading in C++:

  1. Unary Operator Overloading:
    Unary operators, such as +, -, !, and ++, operate on a single operand. Overloading these operators allows for custom behaviors, like negating a value or implementing increment logic specific to a class.

  2. Binary Operator Overloading:
    Binary operators, including +, -, *, and ==, work with two operands. Overloading these enables operations like addition or comparison between objects, facilitating intuitive interactions between instances of a class.

Types of Operator Overloading in C++:

1. Overloading Unary Operator:

// C++ program to show unary

// operator overloading

Overloading Binary Operator:

Unary operators operate on a single operand. Common unary operators include +, -, !, ~, ++, and –.

#include <iostream>

using namespace std;

class Number {

    int value;

public:

    Number(int v = 0) : value(v) {}

    // Overloading the unary ‘-‘ operator

    Number operator-() const {

        return Number(-value);

    }

    void display() const {

        cout << “Value: ” << value << endl;

    }

};

int main() {

    Number num(10);

    num.display();

    Number neg = -num; // Calls the overloaded ‘-‘

    neg.display();

    return 0;

}

2. Binary Operator Overloading

Binary operators work with two operands. Examples include +, -, *, /, and ==.

Example: Overloading the binary + operator

#include <iostream>
using namespace std;

class Complex {
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}

// Overloading the binary ‘+’ operator
Complex operator+(const Complex& obj) const {
return Complex(real + obj.real, imag + obj.imag);
}

void display() const {
cout << real << ” + ” << imag << “i” << endl;
}
};

int main() {
Complex c1(3.5, 2.5), c2(1.5, 4.5);
Complex c3 = c1 + c2; // Calls the overloaded ‘+’
c3.display();

return 0;
}

Output:

 5 + 7i