Ben Packard
Ben Packard

Reputation: 26476

Inheritance in Objective-c and Functions

I have class X, an abstract class, and classes A and B that inherit from it. Classes A and B each have their own 'return_something' function. I have another method elsewhere that calls 'return_something' on a series of objects, all of type X. 'return_something' returns something different depending on whether it is an A or a B, so I can just call id *result = [x return_something).

I can design this all fine, but when I come to implementing it I don't know what to put in class X, the parent. It needs to have a 'return_something' function in order for it to be callable, but the function itself is defined in the child classes. I can declare it in the parent and both children, but I don't have anything to return from the X implementation - the returned object is dependent on the child's re-definition.

This would be fine for a non-returning method, but how am I meant to use inheritance and polymorphism with a function?

Upvotes: 1

Views: 828

Answers (2)

martinr
martinr

Reputation: 3812

Use an objective-C protocol instead of an abstract base class:

@protocol ProtocolX
-(int)return_something;
@end

@interface ClassA : NSObject <ProtocolX> {
}
-init;
-(int)return_something;
@end

@interface ClassB : NSObject <ProtocolX> {
}
-init;
-(int)return_something;
@end

@implementation ClassA : NSObject <ProtocolX>
-(int)return_something { return 1; }
-init { retur [super init]; }
@end

@implementation ClassB : NSObject <ProtocolX>
-(int)return_something { return 3; }
-init { retur [super init]; }
@end

References of type id<ProtocolX> can then be passed around and used:

id<ProtocolX> ref = [[ClassA alloc] init];
int myIntForA = [ref return_something];
[ref release];
ref = [[ClassB alloc] init];
int myIntForB = [ref return_something];
[ref release];

Upvotes: 5

Anon.
Anon.

Reputation: 59993

The simplest thing to do is throw an exception from the "base" function. That way you'll know if it gets called by mistake.

Other languages which provide explicit "abstractness" don't require method bodies for abstract methods.

Upvotes: 6

Related Questions