Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by reference - operator overloading [closed]

In what cases do we pass objects by reference in operator overloading and why? Also, in what cases is operator overloading useful(specific case)?

EDIT: Language: C++

like image 331
Aditya Avatar asked Dec 31 '25 19:12

Aditya


1 Answers

You pass parameters "by reference" either because you want to modify them (which is something you probably don't want to for operators, see below), or simply because it's more efficient to pass a simple pointer than to copy a whole object.

As for "why overload", that's mostly a matter of preference. There are some classic examples, like having a vector class that will let you add vectors or something similar -- basically, these are all good examples because they apply the same meaning that the arithmetic operators have to some new classes: whether you add integers or vectors, it's a natural notation to write "x+y" in both cases. This is also the classical reason for using constant references -- if you write "a=b+c" you don't expect b or c to be modified, and it is definitely good practice to only overload operators if the result of what you are doing is what the reader expects.

Things like smart pointers (or iterators, or other things that "pretend" to be pointers) like to overload operators such as -> or * (the dereference operator, not the multiplication). Same reason, these objects pretend to be pointers, they are meant to be used like pointers, so operator overloading is used to make them look more like pointers.

I have also overloaded the "," operator to feed parameters into a string formatting object -- because it looked good. STL uses overloads for "<<" and ">>" for the same reason; they figured it makes things easier to read.

Recently, I have overloaded a few arithmetic operators and "==" so I can write linear equations in mathematical notation. The code around that builds the coefficient matrix from readable source code, instead of requiring the developer to write a bunch of meaningless numbers. This is also an example where nonconstant references are being used -- however, the result of all this is a row in a matrix representing the equation, so it's precisely what the reader expects.

Basically, stick to one important rule: don't ever do anything unexpected. Overload operators only if the resulting notation like "a+b" is really what someone who doesn't know the internals of your overload expects it to be.

like image 151
Christian Stieber Avatar answered Jan 03 '26 09:01

Christian Stieber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!