C/C++ C++ operator++ overloading, prefix vs postfix

  • Thread starter Thread starter chingkui
  • Start date Start date
  • Tags Tags
    C++ Operator
Click For Summary
The discussion focuses on the overloading of the increment operators (prefix and postfix) in C++. The prefix increment operator is defined as Number& operator++(), which modifies the object and returns a reference to it. The postfix increment operator is defined as Number operator++(int), where the int parameter serves as a dummy argument, allowing the function to distinguish it from the prefix version. The key point of confusion is how the compiler differentiates between the two when calling ++m1 and m2++. It is clarified that this distinction is a built-in feature of the C++ language specification, where the syntax of the increment operations directly translates to the appropriate overloaded function calls based on their signatures.
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).
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

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