jdl
jdl

Reputation: 6323

objective-c: function / method overloading?

The only way I know to do function/method overloading is by way of the base class. Is there a way to do it with in the same class with no inheritance?


Here is an example of the only way I know to do function overloading by way of inheriting the base class:

@interface class1:  NSObject
-(void) print;
@end

@implementation class1
-(void) print
{
    NSLog(@"Hello there");
}
@end



@interface  class2: class1
-(void) print: (int) x;
@end

@implementation class2
-(void) print: (int) x
{
    NSLog(@"Your number is %d", x);
}
@end



int main(void)
{
    class2 *c2 = [class2 new];

    [c2 print];
    [c2 print: 5];
}

result:

Hello there
Your number is 5

Upvotes: 1

Views: 1055

Answers (2)

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

If you override a method that is present in the base class, that is not overloading, that is overriding. The new method replaces the one in the base class. Note that you should give it the same "signature", i.e. the same parameter types and return type in order for it to be polymorphic.

You can't overload methods in Objective-C. They should all have a different name.

Upvotes: 3

Moshe
Moshe

Reputation: 58087

In Objective-C, you cannot overload a function to take different kinds of arguments. For example, the following two methods would not work:

- (NSString *) someStringBasedOnANumber:(int)aNumber{
    //some code here
}

- (NSString *) someStringBasedOnANumber:(double)aNumber{
    //some code here
}

The simplest solution would be to change the method name to follow Apple's method naming convention and rename the methods like so:

- (NSString *) someStringBasedOnAnInt:(int)aNumber{
    //some code here
}

- (NSString *) someStringBasedOnADouble:(double)aNumber{
    //some code here
}

Method names are supposed to be descriptive of the the method's arguments. Overloading goes against this convention, so it would make sense that it's not allowed.

Upvotes: 8

Related Questions