Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator overloading c++

When overloading operators, is it necessary to overload >= <= and !=?

It seems like it would be smart for c++ to call !operator= for !=, !> for operator<= and !< for operator>=.

Is that the case, or is it necessary to overload every function?

like image 777
finiteloop Avatar asked Feb 06 '10 22:02

finiteloop


People also ask

What is the operator overloading in C?

In C++, we can make operators work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.

Does C allow operator overloading?

No, C doesn't support any form of overloading (unless you count the fact that the built-in operators are overloaded already, to be a form of overloading). printf works using a feature called varargs.

What is overloading in C with example?

Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures. This feature is present in most of the Object Oriented Languages such as C++ and Java.

What is an overloading operator?

An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator. Overloaded operators are distinct from overloaded functions, but like overloaded functions, they are distinguished by the number and types of operands used with the operator.


2 Answers

Boost operators might be what you are looking for. These will derive most of your operators based on a few fundamental ones.

That C++ does not provide this automatically makes sense, as one could give totally different meanings to < and >, for example (although it would often be a bad idea).

like image 153
small_duck Avatar answered Oct 08 '22 03:10

small_duck


I am going to take a minority viewpoint here. If you already use boost then using boost operators is not that big of a deal. It may be the correct and tested way to do things but adding boost dependency just for the operators is an overkill.

It is possible to write complex C++ programs without boost (which I personally find aesthetically unpleasant) and so to Keep It Simple (Stupid), to answer OP's question, if you overload operator ==, you should also overload operator !=. Same is true for <, >, ++ etc.

like image 30
Igor Zevaka Avatar answered Oct 08 '22 02:10

Igor Zevaka