November 18, 2022

Operator Overloading

Posted on November 18, 2022  •  2 minutes  • 412 words

A special function operator can be used to overload operators.

  1. Part-1 - link
  2. Part-2 - link

Syntax

return_type operator operator_symbol(arguments)
{
    //body
    return value
}

where operator_symbol can be

%, +, -, *, / , ++, --, !, ==, !=, >=, <= , && , || , =, +=,*=, /=,-=, %= , [ ], &, |, <<, >>, ^, ~

4 operators that cannot be overloaded in C++

1. :: — Scope Resolution operator
2. dot (.) — operator
3. ?: — ternary operator
4. .* — Member pointer selector Operator

Types

  1. Overloading binary-operators (+, -, ..etc)

  2. Overloading unary-operators (++, – , ..etc)

1. Overloading binary-operators (+, -, ..etc)

#include<iostream>

class Complex
{
public:
    Complex()
    {
        real = 0;
        img = 0;
    }

    Complex(double r, double i)
    {
        real = r;
        img = i;
    }

    Complex operator +(const Complex& c)
    {
        Complex ret;
        ret.real = c.real + real;
        ret.img = c.img + img;

        return ret;
    }

    Complex operator -(const Complex& c)
    {
        Complex ret;
        ret.real = c.real - real;
        ret.img = c.img - img;

        return ret;
    }

    void print()
    {
        std::cout << real << " + i" << img << std::endl;
    }

    double real, img;
};

int main(int argc, char const *argv[])
{
    Complex c1(10,20);
    Complex c2(5,10);

    Complex c3 = c1 + c2;
    c3.print();

    Complex c4 = c1 - c2;
    c4.print();

    return 0;
}

Overloading unary-operators (++, – , ..etc)

Types:

  1. prefix operators
Example : ++a , --a
//Syntax
returnType operator symbol()
{
    //body
    return
}
  1. postfix operators
Example : a++ , a--
//Syntax
returnType operator symbol(int)
{
    //body
    return
}

Example Program

class Number
{
public:

    Number()
    {
        value = 0;
    }

    Number(int val)
    {
        value = val;
    }

    // prefix ++
    Number operator ++()
    {
        //body
        Number n;
        n.value = ++value;
        return n;
    }

    // postfix ++
    Number operator ++(int)
    {
        //body
        Number n;
        n.value = value++;
        return n;
    }

    // prefix --
    Number operator --()
    {
        //body
        Number n;
        n.value = --value;
        return n;
    }

    // postfix --
    Number operator --(int)
    {
        //body
        Number n;
        n.value = value--;
        return n;
    }

    int value;
};

int main(int argc, char const *argv[])
{
    Number n1(10);
    Number n2 = ++n1;
    Number n3 = n1++;

    std::cout << "n1:" << n1.value << std::endl;
    std::cout << "n2:" << n2.value << std::endl;
    std::cout << "n3:" << n3.value << std::endl;

    Number n4 = n3--;
    Number n5 = --n4;

    std::cout << "n4:" << n4.value << std::endl;
    std::cout << "n5:" << n5.value << std::endl;

    return 0;
}
Follow me

I work on everything coding and share developer memes