Search code examples
c++operator-overloadingincrementprefixpostfix-mta

How does C++ know that an increment ++ is prefix or postfix when overloading the operator


I understand how to make prefix and postfix incrementers. Within my class DoStuff, I have:

// Prefix; returns the incremented value
friend const DoStuff& operator++(DoStuff& a);
// Postfix: returns the incremented value
friend const DoStuff operator++(DoStuff& a, int);

and outside the class, I have

const DoStuff& operator++(DoStuff& a){
    a.num++;
    return a;
}

const DoStuff operator++(DoStuff& a, int){
    DoStuff before(a.num);
    a.num++;
    return before;
}

for the prefix and postfix incrementers respectively. What I don't understand is how C++ knows that the former is represented by ++a and the latter a++. As far as I can tell, the prefix incrementer references the address & and that somehow means that the ++ operator symbol should come before it. Also, I'm not too sure why the postfix needs an int variable.


Solution

  • When the compiler reads your source code, it can figure out whether you've used a prefix or a postfix. Very simple: either the ++ comes up before or after some object.

    Then the compiler will generate code to call the right function. But what's the name of that function? The people that designed C++ decided to make the function name for overloaded operators operator followed by the operator you're overloading (++, --, = etc), like operator*, operator-, etc.

    But the problem now is that both prefix and postfix increment operators are named operator++. How do you differentiate between them? When you encounter ++var and var++, the compiler generates code to call operator++ for both of them, but you don't want that because now you can't differentiate between the definitions between a postfix and a prefix increment operator.

    To solve this, the same language designers added a dummy parameter, int. This way, the compiler can call operator++(0), or operator++(42) (or whatever number you feel like, it's not important. It's a dummy parameter) when it encounters a postfix ++, and just an operator++() when it encounters a prefix. The parameter is just there for differentiation.

    All in all, this is a language design problem. When it comes to design decisions, naturally, there must've been other solutions (like naming them operator_preinc() and operator_postinc()), but this is what the designers of C++ chose to go with. They could have their reasons, or it could be arbitrarily chosen because maybe all other options weigh about the same.