Operator Overloading in C++

In C++, we can make the operators work for user defined data types. The meaning of the operator will depend on the implementation. This feature is known as operator overloading.

One operator can work in some way on operands of standard data types. And the same operator can work in different ways on operands of user defined data types. This is one type of compile time polymorphism.

We all know how the ‘+’ operator works on standard data types like integer or double. Let’s see how we can give different meaning or behavior for a user-defined data type.

Overloading ‘+’ Operator

#include <iostream>
using namespace std;

class Complex {
public:
    Complex(int r = 0, int i = 0) {
        real = r;
        img = i;
    }

    Complex operator+ (Complex const& rhs) {
        Complex tmp;
        tmp.real = real + rhs.real;
        tmp.img = img + rhs.img;

        return tmp;
    }
    void print() {
        cout << real << " + i" << img << endl;
    }

private:
    int real;
    int img;
};

int main() {
    Complex c1(3, 4);
    Complex c2(5,6);

    Complex res = c1 + c2;

    res.print();

    return 0;
}

Here the Complex class has two members real and img – the real and imaginary parts of a complex number. The compiler does not know how the ‘+’ operator should work for this class.

We defined the behavior of the ‘+’ operator how it will work on two Complex numbers. It will separately add the real and imaginary parts of the two operands and assign them to the result / returned Complex object.

$ g++ -o test test.cpp 
$ ./test 
8 + i10

Overloading the Unary Operator ‘!’

#include <iostream>
using namespace std;

class Complex {
public:
    Complex(int r = 0, int i = 0) {
        real = r;
        img = i;
    }

    bool operator!() const {
        
        return real == 0 && img == 0;
    }
    void print() {
        cout << real << " + i" << img << endl;
    }

private:
    int real;
    int img;
};

int main() {
    Complex c1(0, 0);
    
    if (!c1) {
        cout << "c1 is a NULL complex number." << endl;
    }

    return 0;
}

This example shows how to overload an unary operator for a user defined data type. We overloaded the ‘!’ operator whether a Complex number has 0 value for both the real and imaginary parts.

$ ./test 
c1 is a NULL complex number.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0