What are the basic rules and idioms for operator overloading in C++?

C++Server Side ProgrammingProgramming

When it comes to operator overloading in C++, there are 3 basic rules you should follow. like all such rules, there are so exceptions. These 3 rules are −

  • 1.  Whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded. Instead, provide a function with a well-chosen name. Basically, the first and foremost rule for overloading operators, at its very heart, says:
  • Don’t do it.
  • That might seem strange, but there are only a few cases where operator overloading is appropriate. The reason is, it is hard to understand the semantics behind the application of an operator unless the use of the operator in the application domain is well known and undisputed.
  • 2.  always stick with the operator’s well-known semantics. C++ poses no limitations on the semantics of overladen operators. Your compiler can with happiness settle forcode that implements the binary + operator to reckon from its right quantity. However, the users of such associate operator would never suspect the expression a + b to subtract a from b.
  • 3.  Always provide all out of a set of related operations.
  • Operators are related to each other and to other operations. If your type supports a + b, users will expect to be able to call a += b, too. If it supports prefix increment ++a, they will expect a++ to work as well. If they can check whether a < b, they will most certainly expect to also to be able to check whether a > b. If they can copy-construct your type, they expect assignment to work as well.
  • In most cases you dont need operator over loading and should only overload operators when they are will defined and well suited to the situation. This post is inspired by https://stackoverflow.com/a/4421708/3719089.
Published on 15-Feb-2018 15:52:09