Please explain in detail with examples. Thank you
views:
76answers:
2
+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
2010-10-23 18:24:26
@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
2010-10-23 18:29:51
@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
2010-10-23 18:32:44
@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
2010-10-23 18:35:02
@sepp - As you say, I meant wetware debuggers not the software type :)
bemace
2010-10-23 18:36:50
@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
2010-10-23 18:38:21
@bemace: I know :)
Onkelborg
2010-10-23 18:39:26
@bemace: You can still create an ordinary method which *lies*: `MyInt add(MyInt i) { return new MyInt(this.value - i.value); }`
dalle
2010-10-23 18:41:43
@dalle You don't need to lie. Take for example `event += listener`. Why would events and listeners add up?
badp
2010-10-23 18:43:35
@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
2010-10-23 18:50:47
@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
2010-10-23 21:54:07
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?