C++ - Operator Overloading
Pushpender Singh
Posted on December 30, 2019
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:-
- Prefix - first operator then variable/object
- 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.
- void is return type
- operator is keyword
- ++ is an operator
- () are parenthesis with no parameters
- {} 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
- You can't overload ::, ., ->, ?: operators.
- 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.
Posted on December 30, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.