tags:

views:

76

answers:

2

Please explain in detail with examples. Thank you

+2  A: 

Operator overloading is a feature where the language allows you to define operators for your own types, so that you can write e.g. o1 + o2 where o1 and o2 are instances of your own type, instead of built-in types.

Operator-overloading is not specific to C++, but it's not available in java. Here's an example in Python:

class Vector3D():
  def __init__(self, x, y, z):
    self.x = x
    self.y = y
    self.z = z
  def __repr__(self):
    return "Vector<%f,%f,%f>" % (self.x, self.y, self.z)
  def __add__(self, other):
    return Vector3D(self.x + other.x,
                    self.y + other.y,
                    self.z + other.z)

a = Vector3D( 1, 2, 3)
b = Vector3D(-1,-2,-3)
print a+b # Vector<0.000000,0.000000,0.000000>
sepp2k
@Maxood - It's also a fantastic way to write extremely confusing code when taken too far. Any benefits of operator overloading should be weighed against potential debugging and maintenance issues.
bemace
@bernace: Why would it complicate debugging? Overloaded operators show up in the stack just like any other function, no? Readability/understandability is another issue, of course. You should never overload operators to do something different than their traditional meaning (*cough* `<<`).
sepp2k
@bemace: There are many uses for operator overloading like an implementation of a Big Int, or working with dates. But everything that can be abused is going to be abused.. :)
Onkelborg
@sepp - As you say, I meant wetware debuggers not the software type :)
bemace
@Onkel - I'm not trying to say it should never be done, just cautioning him because when people first discover hammers, they tend to see lots and lots of nails
bemace
@bemace: I know :)
Onkelborg
@bemace: You can still create an ordinary method which *lies*: `MyInt add(MyInt i) { return new MyInt(this.value - i.value); }`
dalle
@dalle You don't need to lie. Take for example `event += listener`. Why would events and listeners add up?
badp
@badp: I agree with what sepp2k wrote: "You should never overload operators to do something different than their traditional meaning". According to me, your example is an example of a design flaw.
dalle
@dalle go tell that to the .net developers out there :) [ (related tutorial, featuring the line `List.Changed += new ChangedEventHandler(ListChanged);`) ](http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx)
badp
A: 

Operator-overloading it's not available in java, but it's not disadvantage. Instead of writing o1 + o2 you can write o1.sum(o2). Is there any difference?

Actually -- yes. It might be a positive or negative difference, but it's a difference nonetheless.
badp
Ehrm, yes there's a difference. `x = x.add(a.multiply(b).add(b.multiply(c)))` is a huge difference, readability wise, from `z += a*b + b*c`.
sepp2k