Asha
Asha

Reputation: 11232

Is it allowed to name the parameter in postfix operator ++?

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

Upvotes: 26

Views: 459

Answers (3)

Prasoon Saurav
Prasoon Saurav

Reputation: 92874

a++ is equivalent to a.operator++(0);. Your code is valid

13.5/7

When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero.

Upvotes: 11

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76856

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.

Upvotes: 20

Alok Save
Alok Save

Reputation: 206586

Yes, it is valid the int as a parameter it only a policy enforcing parameter to distinguish between prefix and postfix operators. The passed parameter will be received as an argument, which is the behavior you see & it is prfectly defined behavior.

Upvotes: 8

Related Questions