B
B
Bogdan2021-07-24 23:37:47
C++ / C#
Bogdan, 2021-07-24 23:37:47

How to overload the operator and not cause the hatred of colleagues?

I am learning OOP on my own small project. Faced with the question of how to gracefully organize addition in a simple class. The class contains only 2 variables:

qint64 value; 
pm_currency_t currency; // тип валюты

On the one hand, I want to implement the ability to add for this class, on the other hand, I do not want to allow addition with a different type of currency.
How good would it be to overload '+' for this class?
When trying to add up different currencies, what would be the best response: returning null_ptr, throwing an exception, something else?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2021-07-24
@Nadgob

1) In this case, the idea is good, since the semantics will not be broken, but on the condition that
2) In case of a currency mismatch, you will throw an exception.
Explanation: If you return a non-currency (nullptr, false, doesn't matter), you will break the addition semantics, and you shouldn't do that. So the error should be handled in an exception.
Problem: If such exceptions occur frequently (for example, it is part of the business logic), you will end up with a slightly more sluggish program. In this case, it is better to abandon operator overloading and write a regular method.
If the currency is already known to you at the compilation stage, remake your class into a template and do all the checks already at the compilation stage - this is the best option.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question