views:

108

answers:

3

Is it possible to override operator use in Objective-C?

For example

myClassInstance + myClassInstance

calls a custom function to add the two.

+3  A: 

No, you can't do this in Objective-C.

Vadim Shender
+8  A: 

Operator overloading is not a feature of Objective-C. If two instances of your classes can be added together, provide a method and allow them to be added using that method:

Thing *result = [thingOne thingByAddingThing:thingTwo];

Or, if your class is mutable:

[thingOne addThing:thingTwo];
dreamlax
+1  A: 

First, operator overloading is evil. Second, C doesn't have operator overloading, and Objective-C is a proper superset of C, which only adds a handful of keywords and a messaging syntax.

That being said, if you're using Apple's development environment, you can use Objective-C++ instead of Objective-C, which gives you access to all of C++'s mistakes and misfeatures, including operator overloading. The simplest way to use Objective-C++ is just to change the extension on your implementation files from ".m" to ".mm"

NSResponder
I don't think it's fair to categorically say it's evil. It doesn't generally seem to pose a big problem in Smalltalk, Ruby, Python or Haskell.
Chuck
Having worked on several large python projects, operator overloading can very much be evil.... Lost countlessnhours to buggy overloads. Mostly in trying to find the damned things.
bbum
Smalltalk doesn't have operator overloading, it has binary messages which behave the same as all the other messages.
JeremyP