Hi
when I look at this website http://www.parashift.com/c++-faq-lite/operator-overloading.html,
I don't quite understand for the section 13.14 about prefix++ and postfix++.

Number x = /* ... */;
++x; // calls Number::operator++(), i.e., calls x.operator++()
x++; // calls Number::operator++(int), i.e., calls x.operator++(0)
why ++x is calling x.operator++() while x++ is calling calls x.operator++(0)?

Recommended Answers

All 5 Replies

This is the important part:

Since the prefix and postfix ++ operators can have two definitions, the C++ language gives us two different signatures. Both are called operator++(), but the prefix version takes no parameters and the postfix version takes a dummy int.

In other words, if one didn't have a dummy int, there'd be no way to disambiguate them.

but I don't understand how to know there is a dummy int for x++ while ++x does not.

If you would have been given an options to implement operator++() which would work for both versions of ++, how would you do it?
You need to find some way to distinguish between both of them.

Number x = /* ... */;
++x; // calls Number::operator++(), i.e., calls x.operator++()
x++; // calls Number::operator++(int), i.e., calls x.operator++(0)

Seems to me that you answered your own question with the above.
That IS the overload method.
As they say: "It is what it is."
You looked it up, NOW YOU KNOW...

thank you all.
say for example, objectA=objectB, then I know objectA.operator=(objectB)
but for ++x and x++, I don't know x.operator++() or x.operator++(0) will be called

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.