C++ operator++ overloading, prefix vs postfix

  • Context: C/C++ 
  • Thread starter Thread starter chingkui
  • Start date Start date
  • Tags Tags
    C++ Operator
Click For Summary
SUMMARY

The discussion focuses on the overloading of the increment operator (++) in C++, specifically the differences between prefix and postfix implementations. The prefix version is defined as Number& operator++(), while the postfix version is defined as Number operator++(int). The distinction lies in the signatures, where the postfix version includes an integer parameter that acts as a dummy argument. This design allows the C++ compiler to differentiate between the two calls, translating ++m1 to operator++() and m2++ to operator++(int).

PREREQUISITES
  • Understanding of C++ operator overloading
  • Familiarity with C++ function signatures
  • Knowledge of C++ class constructors and destructors
  • Basic understanding of C++ memory management
NEXT STEPS
  • Study C++ operator overloading best practices
  • Learn about C++ copy constructors and their implications
  • Explore the C++ language specification regarding operator overloading
  • Investigate performance considerations in C++ operator implementations
USEFUL FOR

C++ developers, software engineers, and computer science students interested in mastering operator overloading and enhancing their understanding of C++ language features.

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?
 
Technology news on Phys.org
The prefix and postfix versions have different signatures. The (int) argument to the postfix version of operator++ is a dummy argument. It's a built-in feature of the language specification that ++m1 translates to a call to operator++(), m2++ to a call to operator++(int).
 

Similar threads

Replies
53
Views
5K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 25 ·
Replies
25
Views
3K
  • · Replies 31 ·
2
Replies
31
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 52 ·
2
Replies
52
Views
4K
Replies
5
Views
6K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 89 ·
3
Replies
89
Views
6K