views:

143

answers:

2

Is function overloading possible in Objective C ?
Well,Most of the programmers says no,
But it looks like possible,
for example:

-(int)AddMethod:(int)X :(int)Y
{
    return X + Y;
}
-(int)AddMethod:(int)X
{
    return X;
}

to call 1st one write [self AddMethod :3];
to call last one write [self AddMethod: 3 :4];

+3  A: 

No, it is not, mostly because Objective-C doesn't use functions, it uses methods.

Method overloading, on the other hand, is possible. Sort of.

Consider, if you will, a class with a method take an argument on the form of either an NSString * or a const char *:

@interface SomeClass : NSObject {

}

- (void)doThingWithString:(NSString *)string;
- (void)doThingWithBytes:(const char *)bytes;

@end

While the method itself won't go around choosing the proper method with a given input; one could still say that doThing: was overloaded, at least in the sense that the two methods taking a different parameter to achieve the same functionality.

Williham Totland
What does it mean by 15.?
vodkhang
Answers must be at least 15 characters long; so I fleshed mine out a bit. ;)
Williham Totland
The example is not even *sort of* overloading, those are simply two different methods for which the naming implies some semantic relation. Its just the commonly used alternative in the absence of overloading.
Georg Fritzsche
@Georg: Which, in essence, is how overloading is implemented in, say, C++: Overloaded methods have the same name in code, but their actual, mangled names are different, and the appropriate one is chosen at compile time. The same principle is at work here, the only difference being that the programmer chooses the correct "mangled" name, not the compiler.
Williham Totland
@Williham Totland: Name mangling is just an implementation detail. There's nothing to say that a C++ compiler/linker has to use name mangling.
JeremyP
Besides name mangling being an implementation detail, overloading is a language feature with all the bundled benefits (e.g. in C++ usage of only one function name in a generic context).
Georg Fritzsche
@Georg Fritzsche: some people would argue that's not a benefit :)
JeremyP
+6  A: 

Method overloading is not possible in Objective-C. However, your example actually will work because you have created two different methods with different selectors: -AddMethod:: and AddMethod:. There is a colon for each interleaved parameter. It's normal to put some text in also e.g. -addMethodX:Y: but you don't have to.

JeremyP
You don't *have* to label the second parameter, but really… you have to. There's no reason to make your code intentionally obtuse.
kubi
@kubi: Completely agree. It's the same kind of "don't have to" as in "you don't have to use letters in C variable names, you can just use strings of underscores".
JeremyP