Hi i am currently learning c++ and just went through operator overloading.My question is in what situations would this be used for
Hi i am currently learning c++ and just went through operator overloading.My question is in what situations would this be used for
Truth be told, not every class needs overloaded operators. Most operations are expected to stand for themselves (2 + x) or mirror something the language made you learn (as in *ptr). Probably, the most important operator you could write is assignment. Overloaded operators become more convenient when you start using the STL to do things: certain algorithms require operator<, or operator().
Suppose you wanted to implement matrices, so you define yourself a new class `Matrix`, probably as a template. Matrices have well defined multiplication, addition and transpose operations. You could implement these by overloading `operator*`, `operator+` and either `operator!` or `operator~` instead of implementing them as member functions `add()`, `multiply()` and `transpose()`. That would make the code operating on `Matrix` type variables look and read more natural. Which is one of the benefits of operator overloading.
Disclaimer: This post shows my ignorance at the time of its making. I claim ownership of but not responsibility for all errors in it. Reference at your own peril.