I am not using this code in any production environment, it is just for my understanding. Is this code valid (i.e. can I define my postfix operator like this?):
class A { public: A& operator++(int n) { std::cout<<"N is:"<<n<<"\n"; return *this; } }; int main() { A a; a++; a.operator ++(10); }
On VS2008, I get the output as:
N is 0
for first call and
N is 10
for second call
Postfix operators are unary operators that work on a single variable which can be used to increment or decrement a value by 1(unless overloaded).
The dummy parameter is simply there to distinguish between the postfix and prefix operators. The name ++ or -- is the same in both cases, so there has to be some way to specify which one you're defining.
A function call is a postfix expression consisting of a function designator followed by parentheses. The order of evaluation of any expressions in the function parameter list is undefined, but there is a sequence point before the actual call.
This behavior is legal and well defined in 13.5.7:
Calling operator++ explicitly, as in expressions like a.operator++(2), has no special properties: The argument to operator++ is 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With