Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to return a reference to the object when overloading a pre-increment operator?

Can I use:

MyClass& MyClass::operator++ () {
    a++;  // private var of MyClass
    return (*this);
}

Or it can be:

MyClass MyClass::operator++ ();

What's the difference?


Thanks for answers. I have another issue.

Many people do something like that:

MyClass& MyClass::operator++();
MyClass MyClass::operator++(int);

Isn't it illogical? Please give some examples if you can.

I know that the first version is pre-increment and the second is post-increment, but i ask why the first one returns reference but the second one not? It is in the same code (class), and the same use of the code.

like image 683
name3r123 Avatar asked Jun 16 '11 16:06

name3r123


1 Answers

You can return whatever you want. void, reference to self, copy of self, something else. Whichever you prefer (or need).

If you plan using the ++ operator in chained expressions (like (++obj).something()) then return a reference. In you don't, then void is just fine.

Remember that in the end, operators are just like normal methods: you can do whatever you want with them, provided you respect their prototype.

like image 149
user703016 Avatar answered Oct 23 '22 15:10

user703016