[C++] Overloading operator+

Started by
13 comments, last by Chuncho 13 years, 3 months ago
So, is it correct to pass a value by const-reference in this situation? For what I read, it isn't, so I won't do it. But is it always incorrect, or there are some situations where is correct?

What if I pass the value just as const?

Like : ...::operator+(const int)...

Would that be correct? Because I'm not supossed to change the value of that argument.

Thanks again. :)
Advertisement

So, is it correct to pass a value by const-reference in this situation? For what I read, it isn't, so I won't do it. But is it always incorrect, or there are some situations where is correct?

What if I pass the value just as const?

Like : ...::operator+(const int)...

Would that be correct? Because I'm not supossed to change the value of that argument.

Thanks again. :)
You can do that, but using const in conjunction with pass-by-value only serves to make sure that the function doesn't internally modify the copy of that value. E.g. It means that you can look at the function signature and know that the value will be the same at the end of the function as it was at the top.
It enforces things upon itself rather than enforcing things on the caller.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

'Chuncho' said:

So, is it correct to pass a value by const-reference in this situation? For what I read, it isn't, so I won't do it. But is it always incorrect, or there are some situations where is correct?

What if I pass the value just as const?

Like : …::operator+(const int)…

Would that be correct? Because I'm not supossed to change the value of that argument.

Thanks again. :)
You can do that, but using const in conjunction with pass-by-value only serves to make sure that the function doesn't internally modify the copy of that value. E.g. It means that you can look at the function signature and know that the value will be the same at the end of the function as it was at the top.
It enforces things upon itself rather than enforcing things on the caller.



Ok, now I'm much clear. Thanks a lot again. :)

So, is it correct to pass a value by const-reference in this situation? For what I read, it isn't, so I won't do it. But is it always incorrect, or there are some situations where is correct?

It would be correct, but inefficient, to pass an int by const reference. For primitives passing by const reference adds overhead for no particular value. (Unless for some reason the reference needs to be stored. This, however, opens a whole mess of issues regarding lifetime.)
Ok, I got it. Thanks a lot again. I really appreciate your help guys.

PS : Sorry for bumping the post again and again.

This topic is closed to new replies.

Advertisement