I have a void operator+
and operator+=
How do I overlap them. I know that if I copy the same code in both functions it will work. I am more curious is there a shorter way without needing to copy the entire code?
Asked
Active
Viewed 146 times
0

Adin Sijamija
- 695
- 2
- 7
- 19
-
Do you really think this is enough details about what you have and why you don't like it? – StoryTeller - Unslander Monica Aug 01 '17 at 10:08
-
call one from another – Shubham Agrawal Aug 01 '17 at 10:08
-
@StoryTeller Sorry I don't get what your trying to say. Can you elaborate? – Adin Sijamija Aug 01 '17 at 10:11
-
@King23 - Amusingly enough, this is what I asked of you. – StoryTeller - Unslander Monica Aug 01 '17 at 10:12
-
@StoryTeller 2 operators(+ and +=) do the same thing to object variables. They receive the same parameters and increase the variables in the identical way. How do I decrease code size by pointing one to the other ? Also I find it amusing how before I was criticized for subjectivity and excess use of details in the description and now the opposite. Guess I went full circle – Adin Sijamija Aug 01 '17 at 10:17
-
Rather than retype your post in a comment, improve you post. Add a bit more code and make sure the issue is clear. And yes, there is a delicate balance to walk. Welcome to SO. – StoryTeller - Unslander Monica Aug 01 '17 at 10:19
1 Answers
0
You can implement one and call that from another, I mean you don't really need to duplicate the code, remember that
c += 20;
is the same as
c = c + 20;
so your + operator should instead of duplicate the code, wisely call the overloaded += operator

ΦXocę 웃 Пepeúpa ツ
- 47,427
- 17
- 69
- 97
-
1No. Conventional wisdom advises to call it the other way around, with parameters properly adjusted. – StoryTeller - Unslander Monica Aug 01 '17 at 10:13
-
Hi! @StoryTeller, thanks for the comment.... but I dont spot the benefit...can you please tell me more – ΦXocę 웃 Пepeúpa ツ Aug 01 '17 at 10:18
-
3`foo operator+ (foo lhs, foo const& rhs) { lhs += rhs; return lhs; }`. This is short, neat, and since C++17 highly susceptible to copy elision and NRVO. – StoryTeller - Unslander Monica Aug 01 '17 at 10:20
-
1wrapping the + operator will involve more copies / moves than the other direction – UKMonkey Aug 01 '17 at 10:20
-