[try Beta version]
Not logged in

 
overloading ++ operators

Sep 24, 2020 at 3:31pm
Hi, I am learning about overloading the ++ operators, and I believe I have the concept understood. But there is a slight problem I am having. I dont understand how the compiler knows the difference between the post and prefix.

I have overloaded both post and prefix. And my book is saying if I call, for instance, a++ , then operator++(int) would be called, but if i call ++a, then operator++, would then be called. But I dont see how the compiler is able to know what one I am wanting to call. Is that something that is just apart of c++, or is it something i am failing to see?
Sep 24, 2020 at 3:32pm
It's just a convention. The C++ language states that the postfix increment operator is implemented with an unused int parameter to differentiate it from the prefix.
Sep 24, 2020 at 4:02pm
But I dont see how the compiler is able to know what one I am wanting to call.

it knows by whether it is ++a or a++ ...

I am not sure what you would need to DO in a class to require having two different versions of ++ for it to work. To me, and in every class I ever did, ++ would just be the same regardless and all that changes is when it is called (via the a++ vs ++a ) which the compiler unravels as it does its thing. But there must be some pattern where distinct versions are needed for some reason, and the language allows it.
Sep 24, 2020 at 4:25pm
post-increment is operator++(int), pre-increment is operator++().

Depending upon the type to which it is applied, there can be considerable performance issues between the two.

The easiest is pre-increment. Take the current value, add 1, save the new value and return the new value - whatever add 1 means in the context of the type.

post-increment means take a copy of the current value, add 1, save the new value and return the value of the copy. Depending upon the type, doing a copy could be significant.

That's why, if there is a choice, pre-increment should always be chosen. It doesn't really matter for a type such as an int, but for custom class it could be - depending upon copy constructor.

Also note that pre-increment should return a ref, whereas post-increment has to return a value.

eg for a simple class where data is a member variable of say type int:

1
2
3
4
5
6
7
8
9
10
11
12
SomeValue& SomeValue::operator++() // prefix
{
    ++data;
    return *this;
}

SomeValue SomeValue::operator++(int) // postfix
{
    SomeValue result = *this;
    ++data;
    return result;
}

Last edited on Sep 24, 2020 at 4:51pm
Topic archived. No new replies allowed.