General question about operator overloading

Hi folks,

At the moment I'm learning about operator overloading.

I think i have more or less got my head around the concept.

Although it strikes me as being very clever, it's not immediately apparent to me what the benefits / uses would be. So far, the examples i have seen perform an action that could easily be achieved in some other way without resorting to operator overloading. But of course the reason for this is the examples have been simple, trivial and just intended for educational purposes.

Could anyone give me some general pointers as to why one would choose to use operator overloading? (without getting too technical, remembering i'm still a noob!)

Thanks in advance! ........... D

You use operator overloading to make a custom iterator (overload increment/decrement, dereference, and maybe some more), a custom function object (overload the call operator), a custom smart pointer (overload dereference), etc

You also use operator overloading to give your type properties such as equality-comparable, regular, or streamable (overload ==, <, or <</>>). That makes it possible to put objects of your class in maps/sets/hash tables, read/write to streams, and generally makes them behave like other programmers and libraries expect objects to behave.

Or you could completely change their meaning and build an embedded DSL such as boost.spirit.
Last edited on
Hi,

Here is a simple example:

Say you have complex objects a,b,c,d for which the normal basic math operations can be applied. So it's easy to explain why one might overload the + operator for example, but you are wondering why not just write an add(a,b) function instead? Now consider this statement, and think about how it would look with function calls: a + b + c / (2 * b) * (c -a) * d

So with operator overloading, one could just write that code as is, but with function calls it would be rather messy.

Now consider all the things Cubbi mentioned, and realise how powerful that is.

Another quick example: overloading < makes it possible for a container of objects to be sorted - the sorting algorithm needs to know how to compare.

Good Luck !!
Thanks guys!

At the IdeasMan: I don't quite follow your example!

Any chance you could write out your example in both ways, firstly as function calls and then with operator overloading, so i can see the difference / see how it works / see the advantage!?

Last edited on
Hi,

Surely you can figure that out ?

Given a function add (a, b) what would you need to do to calculate a + b + c ? Remember, a, b, c etc are several complex objects (like hours minutes seconds in 1 object say), not just an ordinary number.

It's a bit like a cell formula in a spreadsheet, an argument to a function can be a function call.

... / see the advantage!?


I already explained the advantage.

Also, look at the tutorial at the top left of this page.
Topic archived. No new replies allowed.