TheMightyHerb
TheMightyHerb

Reputation: 1

Why does Prefix Incrementor Overload return Type& instead of Type?

Just started doing operator overloads and my teacher didn't go too in depth into them so I was wondering why the return type is different for Prefix/Postfix increment/decrement. When I see the prefix overloads the return type is written as Type&, but the return type for the postfix is written as Type. I made the prefix without the & and the functions both ran properly. Does the return type affect anything or is it just another way to distinguish prefix from postfix?

Upvotes: 0

Views: 536

Answers (3)

Slava
Slava

Reputation: 44268

Main reason is to follow semantics for builtin types in C++ where prefix increment/decrement returns lvalue and postfix one returns rvalue. Details can be found here

Upvotes: 0

Careful Now
Careful Now

Reputation: 272

To add to Emilio's answer postfix incrementing creates a temporary variable and sets that to 1 plus the variable you want to increment where as prefix incrementing increments the actual variable which can have a performance boost in certain cases.

Upvotes: 1

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20759

The reason is to allow chaining:

++ ++ ++ i;

To allow i to triple increment, ++ must return the reference and take the reference. If it returns a temporary copy, the second ++ would increment ... the temporary copy (in fact, a temporary copy won't bind a &, so it will not even compile).

Upvotes: 2

Related Questions