Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prefix operator overloading

I'm overloading the ++ prefix operator using a member function. Here's the prototype:

Test &operator++();

But my doubt comes when I use it for my object like below:

Test t;
++t;

As far I have learned that for any operator overloaded by a member function there should be a object of that same class on left side of that operator. But when I am calling this ++ prefix overloaded operator, I don't need any object of Test class on the left side.

Why?

like image 816
teacher Avatar asked Mar 30 '26 03:03

teacher


2 Answers

Test& operator++();

is always the prefix operator by C++ standard.

In order to override the suffix operator, you need to use another signature:

Test& operator++(int);

These signature are known by the compiler and it will correctly override the right operator.

like image 83
Vincent Robert Avatar answered Apr 01 '26 10:04

Vincent Robert


You just learned incorrectly. How could you have something on the left side of a unary prefix operator?

The same goes for operator~, operator-- and operator!. You don't have anything on the left side of them either.

like image 40
Seth Carnegie Avatar answered Apr 01 '26 09:04

Seth Carnegie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!