teacher
teacher

Reputation: 1015

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?

Upvotes: 2

Views: 3725

Answers (5)

Kos
Kos

Reputation: 72241

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.

That would hold for any binary operator. Pre- and post-incrementations, as well as the dereference operator (*obj) are unary operators. They have a single argument (either a function parameter or implied "this" parameter, depending on how you overload the operator) and for overloaded operators this only argument must be of a class type.

But when I am calling this ++ prefix overloaded operator, I don't need any object of Test class on the left side.

Unary operators don't have a "left" and "right" sides (operands), they only have one operand.


Remember that in your case:

++t;

means just:

t.operator++();

So - in some twisted thinking - t is indeed on the left side. :)

Upvotes: 1

Vincent Robert
Vincent Robert

Reputation: 36120

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.

Upvotes: 3

Operator overloading provides a syntax that is slightly different to any other member (or non-member) function. Whether you implement the pre-increment as a member function or as a free function, you are implementing pre-increment, and the syntax for pre-increment is ++obj.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

Then you have learnt wrong...

Your example is fine; that is indeed how to declare an overload for the pre-increment operator.

Upvotes: 2

Seth Carnegie
Seth Carnegie

Reputation: 75130

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.

Upvotes: 2

Related Questions