Re: pure virtual methods?
Re: pure virtual methods?
- Subject: Re: pure virtual methods?
- From: John Randolph <email@hidden>
- Date: Thu, 24 Jul 2003 14:25:59 -0700
On Thursday, July 24, 2003, at 1:06 PM, Fritz Anderson wrote:
It's in the nature of Objective-C that the compiler doesn't do this
kind of enforcement -- or rather, the @protocol mechanism is the way
the compiler provides for enforcing required methods. You could have
both a root class "doing the dirty work," _and_ a protocol defining
your required methods.
Objective-C defers most class-taxonomy problems to run time. If you
really want your superclass to define a message, and tell senders
(through respondsToSelector:) that it responds to it, but have it yell
at implementors who don't override, you can provide an implementation
that contains just
[self doesNotRecognizeSelector: _cmd];
But there's no equivalent to the "pure virtual" function, reserving a
place in the vtable but not filling it; there is no vtable for you to
maintain. The usual way to not implement a method is simply not to
provide an implementation. Having all the subclasses of a class be the
first implementors of a method is OK.
There also used to be a methods called -subclassResponsibility: and
-notImplemented: in the Object class under NeXTSTEP.
What I'd do today to enforce subclass implementations of given methods
would be something like:
@implementation NSObject (subclassResponsibility)
- (void) subclassResponsibilityForSelector:(SEL) aSel
superclass:(Class) class
{
[NSException raise:@"Missing Method" format:@"subclasses of %@ are
required to implement %@", NSStringFromClass(class),
NSStringFromSelector(_cmd)];
}
@end
@implementation SomeAbstractClass
- requiredMethod
{
[self subclassResponsibilityForSelector:_cmd superclass:[self class]];
}
@end
-jcr
John C. Randolph <email@hidden> (408) 974-8819
Sr. Cocoa Software Engineer,
Apple Worldwide Developer Relations
http://developer.apple.com/cocoa/index.html
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.