1
votes

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?

2
Abstract classes are not something that goes well with Objective-C. There are class-clusters as a kind of replacement. - Georg Schölly
Classes don't have functions in Objective-C. What you're talking about are methods. Just to be clear. - Chuck
Yeah, I was just using function because it returns something. so what would you use to differentiate something with and without a return type (other than void)? - Ben Packard

2 Answers

6
votes

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.

5
votes

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];