DEV Community

Cover image for C++ - Operator Overloading
Pushpender Singh
Pushpender Singh

Posted on • Edited on

C++ - Operator Overloading

What is it?

Giving the normal C++ operators such as +, -, ++, *, additional meaning when they are applied to user defined type such as class.

But why?

Let's say we have created a class called counter.

class Counter
{
private:
    int count;

public:
    Counter() : count(0) {}

    void inc_Count()
    {
        count++;
    }
};

And a object of class Counter name c1

Counter c1;

So in this case if we want to increment count variable, we have to call inc_Count() member function.

Like this:

c1.inc_count();

Don't you think it would be great if we can just do this:-

c1++; // Postfix

// or

++c1; // Prefix

If yes, then Operator Overloading can help us.

Overload "++"

This operator can be use in two notation:-

  1. Prefix - first operator then variable/object
  2. Postfix - first variable then operator

Note:- In our example it doesn't matter, both Prefix or Postfix have same effect.

Let's explore Prefix first

Prefix

Add this into class Counter under Public:

void operator ++ () {
    ++count;
}

To overload an operator we create a member function with operator keyword.

  1. void is return type
  2. operator is keyword
  3. ++ is an operator
  4. () are parenthesis with no parameters
  5. {} are curly braces - it is function body

Now you can do this:-

++c1;

Postfix

Add this into class Counter under Public:

void operator ++ (int) {
    count++;
}

Only difference between Prefix and Postfix is, in Postfix we specify int in () parenthesis (because how C++ Compiler know we want to do Prefix or Postfix) and in function body

Now you can do this:-

c1++;

You can do same with --

Warning

  1. You can't overload ::, ., ->, ?: operators.
  2. You can't create new ones.

There is more if you want to learn, follow this pdf

That's it guys.
Have a nice day.

If you find anything incorrect or know more about it let me know in the comments.

Top comments (0)