C++ operator++ overloading, prefix vs postfix

  • Context: C/C++ 
  • Thread starter Thread starter chingkui
  • Start date Start date
  • Tags Tags
    C++ Operator
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 5K views
chingkui
Messages
178
Reaction score
2
I have seen how people implement the prefix and postfix ++ overloading, which are as follow:

Number& operator++ () // prefix ++
{
// Do work on this.
return *this;
}

Number operator++ (int) // postfix ++
{
Number result(*this); // make a copy for result
++(*this); // Now use the prefix version to do the work
return result; // return the copy (the old) value.
}

What I don't understand is:
When you call ++m1 and m2++, how does the machine know it should call Number& operator++ () for m1 and Number operator++ (int) for m2? I look at it and think about it for a long time, but I still couldn't tell from the syntax how it is done. Did I miss something obvious?
 
Physics news on Phys.org